Java Documentation Overview


experimental.AnimationExpt
Javadoc:
/** * This class tests that the game loop and screen handler are working correctly. * All it does is display the current time in ms and display the number of * frames per second. * * @author Luke Lindsay * */
Source code:
/**
* This class tests that the game loop and screen handler are working correctly.
* All it does is display the current time in ms and display the number of
* frames per second.
*
* @author Luke Lindsay
*
*/
public class AnimationExpt extends JComponent {
private static final long serialVersionUID = 3690191057862473264L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
long l = System.currentTimeMillis();
String str = String.valueOf(l);
g.drawString(str, 100, 100);
}
public static void main(String[] args) {
System.setProperty("SHOWFPS", "true");
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.getContentPane().add(new AnimationExpt());
ScreenHandler screenHandler = new ScreenHandler(f,
ScreenHandler.WINDOWED_MODE);
screenHandler.apply();
GameLoop gameLoop = new GameLoop(screenHandler);
Thread t = new Thread(gameLoop);
t.start();
}
}
Methods:
MethodJavadoc
main
paintComponent
experimental.CheckFreerailsSerializableClasses
Javadoc:
/** Checks that all class that implement FreerailsSerializable are immutable and override equals and hashcode. * * */
Source code:
/** Checks that all class that implement FreerailsSerializable are immutable and override equals and hashcode.
*
*
*/
public class CheckFreerailsSerializableClasses {
static final HashSet<Class> immutableTypes = new HashSet<Class>();
static final HashSet<Class> mutableTypes = new HashSet<Class>();
static Logger logger = Logger.getLogger(CheckFreerailsSerializableClasses.class
.getName());
public static void main(String[] args) {
immutableTypes.clear();
mutableTypes.clear();
immutableTypes.add(String.class);
// Class clazz = StationModel.class;
// System.err.println(overridesHashCodeAndEquals(clazz));
// System.out.println(clazz.isAnnotationPresent(InstanceControlled.class));
// Annotation[] ans = clazz.getAnnotations();
// for (Annotation an : ans) {
// System.err.println(an);
// }
// System.err.println(checkFields(clazz));
testAllClasses();
for (Class c : mutableTypes) {
System.err.println(c.getName());
}
}
static boolean checkFields(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
boolean okSoFar = true;
boolean assertImmutable = clazz.isAnnotationPresent(Immutable.class);
for (Field field : fields) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers)) {
logger.fine("Skipping static field " + field.getName());
continue;
}
Class<?> type = field.getType();
if (type.isPrimitive()) {
continue;
}
// if(!Modifier.isPrivate(modifiers)){
// System.err.println(clazz.getName()+field.getName()+" should be
// private!");
// okSoFar = false;
// }
if (!FreerailsSerializable.class.isAssignableFrom(type)
&& !assertImmutable) {
if (!immutableTypes.contains(type) && !type.isEnum()
&& !type.isAnnotationPresent(Immutable.class)) {
System.err.println(clazz.getName() + "." + field.getName()
+ " {" + type.getName()
+ "} might not be immutable!");
okSoFar = false;
if (!type.isArray())
mutableTypes.add(type);
}
}
}
return okSoFar;
}
@SuppressWarnings("unchecked")
static void testAllClasses() {
ClassLocater locater = new ClassLocater();
Class[] classes = locater.getSubclassesOf(FreerailsSerializable.class);
int classesWithProblems = 0;
for (Class clazz : classes) {
if (clazz.isInterface()) {
logger.fine("Skipping interface " + clazz.getName());
continue;
}
int mods = clazz.getModifiers();
if ((mods & Modifier.ABSTRACT) != 0) {
logger.fine("Skipping abstract class " + clazz.getName());
continue;
}
if (clazz.isAnnotationPresent(InstanceControlled.class)) {
logger.fine("Skipping InstanceControlled class "
+ clazz.getName());
continue;
}
boolean b = overridesHashCodeAndEquals(clazz);
b = b && checkFields(clazz);
if (!b) {
classesWithProblems++;
}
}
System.err.println(classes.length + " classes checked, "
+ classesWithProblems + " have problems");
}
static boolean overridesHashCodeAndEquals(Class clazz) {
try {
boolean okSoFar = true;
Method equals = clazz.getMethod("equals", Object.class);
if (equals.getDeclaringClass().equals(Object.class)) {
System.err.println(clazz.getName() + " does not override "
+ equals.getName());
okSoFar = false;
}
Method hashCode = clazz.getMethod("hashCode");
if (hashCode.getDeclaringClass().equals(Object.class)) {
System.err.println(clazz.getName() + " does not override "
+ hashCode.getName());
okSoFar = false;
}
return okSoFar;
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
Methods:
MethodJavadoc
checkFields
main
overridesHashCodeAndEquals
testAllClasses
experimental.ConnectAllCities
Javadoc:
/** * * @author Luke */
Source code:
/**
*
* @author Luke
*/
public class ConnectAllCities {
static class DistanceComparator implements Comparator<CityModel> {
final int targetX, targetY;
public DistanceComparator(int targetX, int targetY) {
this.targetX = targetX;
this.targetY = targetY;
}
int distSquared(CityModel a) {
int xDist = a.getCityX() - targetX;
int yDist = a.getCityY() - targetY;
return xDist * xDist + yDist * yDist;
}
@Override
public int compare(CityModel a, CityModel b) {
return distSquared(a) - distSquared(b);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException, PathNotFoundException {
SavedGamesManager gamesManager = new SavedGamesManagerImpl();
String[] newMapNames = gamesManager.getNewMapNames();
World w = (World) gamesManager.newMap(newMapNames[0]);
System.out.println(w.getClass());
ServerGameModel gameModel = new ServerGameModelImpl();
String name = "Tester";
Player p = new Player(name, 0);
Move addPlayerMove = AddPlayerMove.generateMove(w, p);
MoveStatus ms = addPlayerMove.doMove(w, Player.AUTHORITATIVE);
w.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
w.setTime(new GameTime(0));
w.set(ITEM.GAME_SPEED, new GameSpeed(10));
w.set(ITEM.GAME_RULES, GameRules.DEFAULT_RULES);
Transaction t = new AddItemTransaction(Transaction.Category.BOND, 0, 1, new Money(50000000));
w.addTransaction(p.getPrincipal(), t);
List<CityModel> citiesUnconnected = new ArrayList<>();
List<CityModel> citiesConnected = new ArrayList<>();
int nCities = w.size(SKEY.CITIES);
System.out.format("There are %d cities.%n", nCities);
for (int i = 0; i < nCities; i++) {
citiesUnconnected.add((CityModel) w.get(SKEY.CITIES, i));
}
CityModel cityA = citiesUnconnected.remove(0);
citiesConnected.add(cityA);
DistanceComparator distanceComparator = new DistanceComparator(cityA.getCityX(), cityA.getCityY());
Collections.sort(citiesUnconnected, distanceComparator);
MapCustomizer mc = new MapCustomizer(w);
int n = citiesUnconnected.size();
for (int i = 0; i < n; i++) {
CityModel cityB = citiesUnconnected.remove(0);
System.out.format("build track to %s%n", cityB.getCityName());
distanceComparator = new DistanceComparator(cityB.getCityX(), cityB.getCityY());
Collections.sort(citiesConnected, distanceComparator);
ImPoint b = cityB.getLocation();
for (int j = 0; j < Math.min(3, citiesConnected.size()); j++) {
cityA = citiesConnected.get(j);
ImPoint a = cityA.getLocation();
mc.buildTrack(a, b);
try {
if (j == 0) {
if (i == 0) {
mc.buildStation(a);
}
mc.buildStation(b);
}
} catch (java.lang.IllegalStateException e) {
//sometimes it is not possible to build the
//stations, e.g. another one is too close.
break;
}
int stationA = mc.getStationId(a);
int stationB = mc.getStationId(b);
if (stationA >= 0 && stationB >= 0) {
//the stations exist.
mc.buildTrain(b, stationA, stationB);
}
}
System.out.format("There are %d stations%n", w.size(p.getPrincipal(), KEY.STATIONS));
citiesConnected.add(cityB);
}
System.out.println(ms);
String[] passwords = {"password"};
gameModel.setWorld(w, passwords);
gamesManager.saveGame(gameModel, "generated.sav");
}
}
Methods:
MethodJavadoc
main/**
experimental.DialogueBoxTester
Javadoc:
/** * This class lets you test dialogue boxes without running the whole game. * * @author lindsal8 * */
Source code:
/**
* This class lets you test dialogue boxes without running the whole game.
*
* @author lindsal8
*
*/
public class DialogueBoxTester extends javax.swing.JFrame {
private static final long serialVersionUID = 4050764909631780659L;
private static final Player TEST_PLAYER = new Player("test player", 0);
private static final FreerailsPrincipal TEST_PRINCIPAL = TEST_PLAYER
.getPrincipal();
private final DialogueBoxController dialogueBoxController;
private World w;
private RenderersRoot vl;
private ModelRootImpl modelRoot;
private Action closeCurrentDialogue = new AbstractAction("Close") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
dialogueBoxController.closeContent();
}
};
;
private TrainDialogueJPanel trainDialogueJPanel = new TrainDialogueJPanel();
/** Creates new form TestGlassPanelMethod. */
private DialogueBoxTester() {
w = new WorldImpl(200, 200);
UntriedMoveReceiver dummyReceiver = new SimpleMoveReceiver(w);
modelRoot = new ModelRootImpl();
modelRoot.setMoveFork(new MoveChainFork());
modelRoot.setMoveReceiver(dummyReceiver);
WagonAndEngineTypesFactory wetf = new WagonAndEngineTypesFactory();
TileSetFactory tileFactory = new TileSetFactoryImpl();
tileFactory.addTerrainTileTypesList(w);
wetf.addTypesToWorld(w);
w.addPlayer(TEST_PLAYER);
try {
vl = new RenderersRootImpl(w, FreerailsProgressMonitor.NULL_INSTANCE);
} catch (IOException e) {
e.printStackTrace();
}
modelRoot.setup(w, TEST_PLAYER.getPrincipal());
ActionRoot actionRoot = new ActionRoot(modelRoot);
actionRoot.setup(modelRoot, vl);
dialogueBoxController = new DialogueBoxController(this, modelRoot);
actionRoot.setDialogueBoxController(dialogueBoxController);
dialogueBoxController.setDefaultFocusOwner(this);
int numberOfCargoTypes = w.size(SKEY.CARGO_TYPES);
StationModel bristol = new StationModel(10, 10, "Bristol",
numberOfCargoTypes, 0);
boolean[] demandArray = new boolean[numberOfCargoTypes];
// Make the stations demand all cargo..
for (int i = 0; i < demandArray.length; i++) {
demandArray[i] = true;
}
Demand4Cargo demand = new Demand4Cargo(demandArray);
bristol = new StationModel(bristol, demand);
w.add(TEST_PRINCIPAL, KEY.STATIONS, bristol);
w.add(TEST_PRINCIPAL, KEY.STATIONS, new StationModel(50, 100, "Bath",
numberOfCargoTypes, 0));
w.add(TEST_PRINCIPAL, KEY.STATIONS, new StationModel(40, 10, "Cardiff",
numberOfCargoTypes, 0));
w.add(TEST_PRINCIPAL, KEY.STATIONS, new StationModel(100, 10, "London",
numberOfCargoTypes, 0));
w.add(TEST_PRINCIPAL, KEY.STATIONS, new StationModel(90, 50, "Swansea",
numberOfCargoTypes, 0));
// Set up cargo bundle, for the purpose of this test code all the trains
// can share the
// same one.
MutableCargoBundle cb = new MutableCargoBundle();
cb.setAmount(new CargoBatch(0, 10, 10, 8, 0), 80);
cb.setAmount(new CargoBatch(0, 10, 10, 9, 0), 60);
cb.setAmount(new CargoBatch(1, 10, 10, 9, 0), 140);
cb.setAmount(new CargoBatch(3, 10, 10, 9, 0), 180);
cb.setAmount(new CargoBatch(5, 10, 10, 9, 0), 10);
w.add(TEST_PRINCIPAL, KEY.CARGO_BUNDLES, cb.toImmutableCargoBundle());
MutableSchedule schedule = new MutableSchedule();
TrainOrdersModel order = new TrainOrdersModel(0, new ImInts(0, 0, 0),
false, false);
TrainOrdersModel order2 = new TrainOrdersModel(1, new ImInts(1, 2, 0,
0, 0), true, false);
TrainOrdersModel order3 = new TrainOrdersModel(2, null, true, false);
schedule.setOrder(0, order);
schedule.setOrder(1, order2);
int scheduleID = w.add(TEST_PRINCIPAL, KEY.TRAIN_SCHEDULES, schedule
.toImmutableSchedule());
w.add(TEST_PRINCIPAL, KEY.TRAINS,
new TrainModel(0, new ImInts(0, 0), scheduleID));
schedule.setOrder(2, order2);
schedule.setOrder(3, order3);
scheduleID = w.add(TEST_PRINCIPAL, KEY.TRAIN_SCHEDULES,
schedule.toImmutableSchedule());
w.add(TEST_PRINCIPAL, KEY.TRAINS,
new TrainModel(1, new ImInts(1, 1), scheduleID));
schedule.setOrder(4, order2);
schedule.setOrderToGoto(3);
schedule.setPriorityOrders(order);
scheduleID = w.add(TEST_PRINCIPAL, KEY.TRAIN_SCHEDULES,
schedule.toImmutableSchedule());
w.add(TEST_PRINCIPAL, KEY.TRAINS,
new TrainModel(0, new ImInts(1, 2, 0), scheduleID));
final MyGlassPanel glassPanel = new MyGlassPanel();
dialogueBoxController.setup(modelRoot, vl);
initComponents();
glassPanel.setSize(800, 600);
this.addComponentListener(new JFrameMinimumSizeEnforcer(640, 480));
this.setSize(640, 480);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
jLabel1 = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
show = new javax.swing.JMenu();
showBrokerScreen = new javax.swing.JMenuItem();
selectEngine = new javax.swing.JMenuItem();
selectWagons = new javax.swing.JMenuItem();
selectTrainOrders = new javax.swing.JMenuItem();
showControls = new javax.swing.JMenuItem();
showTerrainInfo = new javax.swing.JMenuItem();
showStationInfo = new javax.swing.JMenuItem();
showTrainList = new javax.swing.JMenuItem();
showReportBug = new javax.swing.JMenuItem();
throwException = new javax.swing.JMenuItem();
showCargoWaitingAndDemand = new javax.swing.JMenuItem();
showJavaSystemProperties = new javax.swing.JMenuItem();
showNetworthGraph = new javax.swing.JMenuItem();
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/jfreerails/data/south_america.png")));
jLabel1.setText("Press Esc to close dialogue boxes");
jLabel1.setMinimumSize(new java.awt.Dimension(640, 480));
jLabel1.setPreferredSize(new java.awt.Dimension(640, 480));
getContentPane().add(jLabel1, java.awt.BorderLayout.CENTER);
show.setText("Show");
showBrokerScreen.setText("Broker Screen");
showBrokerScreen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newspaperActionPerformed(evt);
}
});
show.add(showBrokerScreen);
selectEngine.setText("Select Engine");
selectEngine.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectEngineActionPerformed(evt);
}
});
show.add(selectEngine);
selectWagons.setText("Select Wagons");
selectWagons.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectWagonsActionPerformed(evt);
}
});
show.add(selectWagons);
selectTrainOrders.setText("Train Orders");
selectTrainOrders
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectTrainOrdersActionPerformed(evt);
}
});
show.add(selectTrainOrders);
showControls.setText("Show game controls");
showControls.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showControlsActionPerformed(evt);
}
});
show.add(showControls);
showTerrainInfo.setText("Show Terrain Info");
showTerrainInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showTerrainInfoActionPerformed(evt);
}
});
show.add(showTerrainInfo);
showStationInfo.setText("Show Station Info");
showStationInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showStationInfoActionPerformed(evt);
}
});
show.add(showStationInfo);
showTrainList.setText("Train List");
showTrainList.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showTrainListActionPerformed(evt);
}
});
show.add(showTrainList);
showCargoWaitingAndDemand.setText("Cargo waiting & demand");
showCargoWaitingAndDemand
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showCargoWaitingAndDemandActionPerformed(evt);
}
});
show.add(showCargoWaitingAndDemand);
showJavaSystemProperties.setText("Java System Properties");
showJavaSystemProperties
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showJavaSystemPropertiesActionPerformed(evt);
}
});
throwException.setText("Throw Exception");
throwException.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
throw new IllegalArgumentException();
}
});
show.add(showJavaSystemProperties);
showNetworthGraph.setText("Show networth graph");
showNetworthGraph
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showNetworthGraphActionPerformed(evt);
}
});
show.add(showNetworthGraph);
showReportBug.setText("Report Bug");
showReportBug
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showReportBug();
}
});
show.add(showReportBug);
jMenuBar1.add(show);
setJMenuBar(jMenuBar1);
}// GEN-END:initComponents
private void showNetworthGraphActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showNetworthGraphActionPerformed
dialogueBoxController.showNetworthGraph();
}// GEN-LAST:event_showNetworthGraphActionPerformed
private void showJavaSystemPropertiesActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showJavaSystemPropertiesActionPerformed
// Add your handling code here:
String s = ShowJavaProperties.getPropertiesHtmlString();
HtmlJPanel htmlPanel = new HtmlJPanel(s);
htmlPanel.setup(modelRoot, vl, closeCurrentDialogue);
dialogueBoxController.showContent(htmlPanel);
}// GEN-LAST:event_showJavaSystemPropertiesActionPerformed
private void formKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_formKeyPressed
if (java.awt.event.KeyEvent.VK_ESCAPE == evt.getKeyCode()) {
dialogueBoxController.closeContent();
}
}// GEN-LAST:event_formKeyPressed
private void showCargoWaitingAndDemandActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showCargoWaitingAndDemandActionPerformed
// Add your handling code here:
CargoWaitingAndDemandedJPanel panel = new CargoWaitingAndDemandedJPanel();
panel.setup(modelRoot, vl, closeCurrentDialogue);
int newStationID = 0;
panel.display(newStationID);
dialogueBoxController.showContent(panel);
}// GEN-LAST:event_showCargoWaitingAndDemandActionPerformed
private void showTrainListActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showTrainListActionPerformed
// Add your handling code here:
dialogueBoxController.showTrainList();
}// GEN-LAST:event_showTrainListActionPerformed
private void showStationInfoActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showStationInfoActionPerformed
// Add your handling code here:
int stationNumber = 0;
dialogueBoxController.showStationInfo(stationNumber);
}// GEN-LAST:event_showStationInfoActionPerformed
private void showTerrainInfoActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showTerrainInfoActionPerformed
// Add your handling code here:
int terrainType = 0;
dialogueBoxController.showTerrainInfo(terrainType);
}// GEN-LAST:event_showTerrainInfoActionPerformed
private void showControlsActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showControlsActionPerformed
// Add your handling code here:
dialogueBoxController.showGameControls();
}// GEN-LAST:event_showControlsActionPerformed
private void selectTrainOrdersActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_selectTrainOrdersActionPerformed
// Add your handling code here:
trainDialogueJPanel.setup(modelRoot, vl, closeCurrentDialogue);
trainDialogueJPanel.display(0);
dialogueBoxController.showContent(trainDialogueJPanel);
}// GEN-LAST:event_selectTrainOrdersActionPerformed
private void selectWagonsActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_selectWagonsActionPerformed
// Add your handling code here:
dialogueBoxController.showSelectWagons();
}// GEN-LAST:event_selectWagonsActionPerformed
private void selectEngineActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_selectEngineActionPerformed
// Add your handling code here:
dialogueBoxController.showSelectEngine();
}// GEN-LAST:event_selectEngineActionPerformed
private void newspaperActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_newspaperActionPerformed
// Add your handling code here:
dialogueBoxController.showBrokerScreen();
//dialogueBoxController.showNewspaper("New headline!");
}// GEN-LAST:event_newspaperActionPerformed
/** Exit the Application. */
private void exitForm(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_exitForm
System.exit(0);
}// GEN-LAST:event_exitForm
public static void main(String args[]) {
DialogueBoxTester test = new DialogueBoxTester();
test.setVisible(true);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JLabel jLabel1;
javax.swing.JMenuBar jMenuBar1;
javax.swing.JMenuItem showBrokerScreen;
javax.swing.JMenuItem selectEngine;
javax.swing.JMenuItem selectTrainOrders;
javax.swing.JMenuItem selectWagons;
javax.swing.JMenu show;
javax.swing.JMenuItem showCargoWaitingAndDemand;
javax.swing.JMenuItem showControls;
javax.swing.JMenuItem showJavaSystemProperties;
javax.swing.JMenuItem showNetworthGraph;
javax.swing.JMenuItem showStationInfo;
javax.swing.JMenuItem showTerrainInfo;
javax.swing.JMenuItem showTrainList;
javax.swing.JMenuItem showReportBug;
javax.swing.JMenuItem throwException;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
exitForm/** Exit the Application. */
formKeyPressed
initComponents/**
main
newspaperActionPerformed
selectEngineActionPerformed
selectTrainOrdersActionPerformed
selectWagonsActionPerformed
showCargoWaitingAndDemandActionPerformed
showControlsActionPerformed
showJavaSystemPropertiesActionPerformed
showNetworthGraphActionPerformed
showStationInfoActionPerformed
showTerrainInfoActionPerformed
showTrainListActionPerformed
experimental.ExptWriteToBuffer
Javadoc:
/** * Experiment to try out reading and writing to a buffer to test serialization * code. * * @author Luke * */
Source code:
/**
* Experiment to try out reading and writing to a buffer to test serialization
* code.
*
* @author Luke
*
*/
public class ExptWriteToBuffer {
private static final Logger logger = Logger
.getLogger(ExptWriteToBuffer.class.getName());
public static void main(String[] args) {
try {
Point p = new Point(10, 10);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objectOut = new ObjectOutputStream(out);
objectOut.writeObject(p);
objectOut.flush();
byte[] bytes = out.toByteArray();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ObjectInputStream objectIn = new ObjectInputStream(in);
Object o = objectIn.readObject();
Point p2 = (Point) o;
if (p.equals(p2)) {
logger.info("The two objects are equal!");
} else {
logger.info("The two objects are not equal!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Methods:
MethodJavadoc
main
experimental.GenerateDependenciesXmlAndHtml
Javadoc:
/** * This class generates an ant script that checks the dependencies between * packages and also generates an html page that illustrates the allowed * dependencies. The checkdep target on the generated ant script tests the * dependencies of packages. It does this by copying the contents of the package * in question together with the contents of the packages it is allowed to * depend on to a temporary directory, then compiling the contents of the * package. If the packaged depends on classes other than those contained in the * packages it is allowed to depend on, the compile will fail. * * @author Luke * */
Source code:
/**
* This class generates an ant script that checks the dependencies between
* packages and also generates an html page that illustrates the allowed
* dependencies. The checkdep target on the generated ant script tests the
* dependencies of packages. It does this by copying the contents of the package
* in question together with the contents of the packages it is allowed to
* depend on to a temporary directory, then compiling the contents of the
* package. If the packaged depends on classes other than those contained in the
* packages it is allowed to depend on, the compile will fail.
*
* @author Luke
*
*/
public class GenerateDependenciesXmlAndHtml {
private static final Logger logger = Logger
.getLogger(GenerateDependenciesXmlAndHtml.class.getName());
private PrintWriter xmlWriter;
private PrintWriter htmlWriter;
private ArrayList<String> packages = new ArrayList<String>();
private boolean started = false;
private boolean startedBlock = false;
private String sig;
public static void main(String[] args) {
try {
new GenerateDependenciesXmlAndHtml("checkdep.xml", "src"
+ File.separator + "docs" + File.separator
+ "dependencies.html");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private GenerateDependenciesXmlAndHtml(String xmlFilename,
String htmlFilename) throws FileNotFoundException {
Date d = new Date();
sig = this.getClass().getName() + " on " + d;
// Setup writers
File xmlFile = new File(xmlFilename);
xmlWriter = new PrintWriter(new FileOutputStream(xmlFile));
File htmlFile = new File(htmlFilename);
htmlWriter = new PrintWriter(new FileOutputStream(htmlFilename));
String[] basePackages = { "jfreerails/util/*" };
start();
startBlock("All");
add(basePackages);
add("jfreerails/world/**/*");
add("jfreerails/move/**/*");
add("jfreerails/controller/*");
add("jfreerails/network/*");
add(new String[] { "jfreerails/server/**/*", "jfreerails/client/**/*" });
add("jfreerails/launcher/**/*");
add("jfreerails/experimental/**/*");
endBlock();
startBlock("World");
add(basePackages);
add("jfreerails/world/common/*");
add(new String[] { "jfreerails/world/terrain/*",
"jfreerails/world/cargo/*", "jfreerails/world/train/*",
"jfreerails/world/station/*" });
add("jfreerails/world/track/*");
add("jfreerails/world/accounts/*");
add("jfreerails/world/player/*");
add("jfreerails/world/top/*");
endBlock();
startBlock("Server");
add(basePackages);
add("jfreerails/world/**/*");
add("jfreerails/move/**/*");
add("jfreerails/controller/*");
add("jfreerails/network/*");
add("jfreerails/server/common/*");
add("jfreerails/server/parser/*");
add("jfreerails/server/*");
endBlock();
startBlock("Client");
add(basePackages);
add("jfreerails/world/**/*");
add("jfreerails/move/**/*");
add("jfreerails/controller/*");
add("jfreerails/network/*");
add("jfreerails/client/common/*");
add("jfreerails/client/renderer/*");
add("jfreerails/client/view/*");
add("jfreerails/client/top/*");
endBlock();
finish();
xmlWriter.flush();
htmlWriter.flush();
logger.info(sig);
logger.info("Wrote " + xmlFile);
logger.info("Wrote " + htmlFile);
}
private void start() {
assert !started;
startXml();
htmlWriter.write("<html>\n");
htmlWriter.write("<title>Dependencies between packages</title>\n");
htmlWriter.write("<p><code>This file was generate by " + sig
+ "</code></p>\n");
htmlWriter.write("<h1>Dependencies between packages</h1>\n");
htmlWriter
.write("<p>The figures below show the dependencies: packages may only depend, i.e. import classes and interfaces, from packages below.</p>\n");
started = true;
}
private void startBlock(String blockName) {
assert started;
assert !startedBlock;
startedBlock = true;
htmlWriter.write("<h2>" + blockName + "</h2>");
xmlWriter
.write("\n\t\t<!-- Setup the directory where the legal dependencies are stored -->\n");
xmlWriter.write("\t\t<delete dir=\"dependencies\" />\n");
xmlWriter.write("\t\t<mkdir dir=\"dependencies\" />\n");
}
private void endBlock() {
assert started;
assert startedBlock;
htmlWriter
.write("<table width=\"100%\" border=\"1\" cellpadding=\"10\" cellspacing=\"10\" bordercolor=\"#333333\" bgcolor=\"#FFFFFF\">\n");
for (int i = packages.size() - 1; i >= 0; i--) {
String packageName = packages.get(i);
htmlWriter.write("<tr bgcolor=\"#FFCCCC\"> \n");
htmlWriter.write("<td height=\"50\" bgcolor=\"#FFCC66\">"
+ packageName + "</td>\n");
htmlWriter.write("</tr>\n");
}
htmlWriter.write("</table>\n");
packages.clear();
xmlWriter.write("\n\t\t<!-- End Block -->\n");
xmlWriter.write("\t\t<echo message=\"End Block\"/>\n");
startedBlock = false;
}
private void startXml() {
// Start the file.
xmlWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
xmlWriter
.write("<project basedir=\".\" default=\"checkdep\" name=\"checkdep\">\n");
xmlWriter.write("\t<description>This ant script was generated by "
+ sig
+ " to check the dependencies for jfreerails.</description>\n");
// Set the properties.
// Add the compile target.
xmlWriter
.write("\n\t<target description=\"Build everything except JUnit test-classes\" name=\"compile\">\n");
xmlWriter.write("\t\t<mkdir dir=\"build\" />\n");
xmlWriter
.write("\t\t<javac destdir=\"build\" fork=\"true\" srcdir=\"src\" source=\"1.5\">\n");
xmlWriter.write("\t\t\t<exclude name=\"**/*Test.java\" />\n");
xmlWriter.write("\t\t </javac>\n");
xmlWriter.write("\t</target>\n");
// Start the check depend target.
xmlWriter
.write("\n\n\t<target depends=\"compile\" description=\"Tests whether dependencies between packages conform to the rules defined in this target\" name=\"checkdep\">\n");
}
private void add(String packageName) {
add(new String[] { packageName });
}
private void add(String[] packageNames) {
assert started;
assert startedBlock;
String packagesString = "";
for (int i = packageNames.length - 1; i > 0; i--) {
packagesString += convertToPackageName(packageNames[i]) + ", ";
}
packagesString += " " + convertToPackageName(packageNames[0]);
// The html writer will use this later.
packages.add(packagesString);
xmlWriter.write("\n\t\t<!-- New row: " + packagesString + " -->\n");
xmlWriter.write("\t\t<echo message=\"New row: " + packagesString
+ "\"/>\n");
// Include the source files we are going to compile.
for (String packageName : packageNames) {
xmlWriter.write("\t\t<echo message=\"Check dependencies for "
+ packageName + "\"/>\n");
xmlWriter.write("\t\t<delete dir=\"temp\" />\n");
xmlWriter.write("\t\t<mkdir dir=\"temp\" />\n");
// First copy the files we are testing.
xmlWriter.write("\t\t<copy todir=\"temp\">\n");
xmlWriter.write("\t\t<fileset dir=\"src\">\n");
xmlWriter.write("\t\t\t<include name=\"" + packageName
+ ".java\" />\n");
// Exclude unit tests.
xmlWriter.write("\t\t\t<exclude name=\"**/*Test.java\" />\n");
xmlWriter.write("\t\t</fileset>\n");
xmlWriter.write("\t\t</copy>\n");
xmlWriter
.write("\t\t<javac fork=\"true\" srcdir=\"temp\" source=\"1.5\" classpath=\"dependencies\">\n");
// Include the files we are going to compile.
xmlWriter.write("\t\t\t<include name=\"" + packageName
+ ".java\" />\n");
xmlWriter.write("\t\t</javac>\n");
xmlWriter.write("\t\t<delete dir=\"temp\" />\n");
}
// Copy the files we have just tested to the dependencies directory.
xmlWriter.write("\t\t<copy todir=\"dependencies\">\n");
xmlWriter.write("\t\t<fileset dir=\"build\">\n");
for (int i = 0; i < packageNames.length; i++) {
xmlWriter.write("\t\t\t<include name=\"" + packageNames[i]
+ ".class\" />\n");
}
xmlWriter.write("\t\t\t<exclude name=\"**/*Test.class\" />\n");
xmlWriter.write("\t\t</fileset>\n");
xmlWriter.write("\t\t</copy>\n");
}
private String convertToPackageName(String packagesString) {
if (!isPackageNameOk(packagesString)) {
throw new IllegalArgumentException(packagesString);
}
packagesString = packagesString.replace('/', '.');
/*
* Remove the last two characters, so that jfreerails.world.**.* - >
* jfreerails.world.** and jfreerails.util.* -> jfreerails.util
*/
packagesString = packagesString.substring(0,
packagesString.length() - 2);
return packagesString;
}
static boolean isPackageNameOk(String s) {
return s.matches("(([a-zA-Z]*)/)*\\*")
|| s.matches("(([a-zA-Z]*)/)*\\*\\*/\\*");
}
private void finish() {
assert started;
assert !startedBlock;
// finish the file.
xmlWriter.write("\t\t<delete dir=\"temp\" />\n");
xmlWriter.write("\t\t<delete dir=\"dependencies\" />\n");
xmlWriter.write("\t</target>\n");
xmlWriter.write("</project>\n");
htmlWriter.write("</html>\n");
started = false;
}
}
Methods:
MethodJavadoc
add/**
add
convertToPackageName
endBlock
finish
isPackageNameOk
main
start
startBlock
startXml
experimental.GenerateTrainHighlights
Javadoc:
/** * Generates image files that can be used to indicate that a train has focus or * is selected. The image files are semi transparent and are intended to be * rendered 'under' the images of the train's engine and wagons. * * * @author Luke */
Source code:
/**
* Generates image files that can be used to indicate that a train has focus or
* is selected. The image files are semi transparent and are intended to be
* rendered 'under' the images of the train's engine and wagons.
*
*
* @author Luke
*/
public class GenerateTrainHighlights {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ImageManager imageManager = new ImageManagerImpl(
"/experimental/", "/experimental/");
UIDefaults lookAndFeelDefaults = UIManager.getLookAndFeelDefaults();
Color selection = (Color) lookAndFeelDefaults.get("List.selectionBackground");
selection = makeTransparent(selection, 128);
String filename = "selected_%s.png";
gen(imageManager, selection, filename);
Color focus = (Color) lookAndFeelDefaults.get("TabbedPane.focus");
focus = makeTransparent(focus, 128);
filename = "focused_%s.png";
gen(imageManager, focus, filename);
try {
imageManager.writeAllImages();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void gen(ImageManager imageManager, Color selection, String filename) {
for (Step step : Step.getList()) {
int tileSize = 30;
Image smallImage = imageManager.newBlankImage(tileSize, tileSize);
Graphics2D g2 = (Graphics2D) smallImage.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(3));
double arcRadius = 5;
g2.rotate(step.getDirection(), tileSize/2, tileSize/2);
RoundRectangle2D roundedRectangle = new RoundRectangle2D.Double(7, 3, 16, 26, arcRadius, arcRadius);
g2.setColor(selection);
g2.fill(roundedRectangle);
g2.dispose();
String name = String.format(filename, step.toAbrvString());
imageManager.setImage(name, smallImage);
}
}
static Color makeTransparent(Color before, int alpha){
return new Color(before.getRed(), before.getGreen(), before.getBlue(), alpha);
}
}
Methods:
MethodJavadoc
gen
main/**
makeTransparent
experimental.LineDrawTrackPieceView
Javadoc:
/** * This TrackPieceRenderer renders track pieces by drawing lines so avoids the * need to load images. * * @author Luke Lindsay */
Source code:
/**
* This TrackPieceRenderer renders track pieces by drawing lines so avoids the
* need to load images.
*
* @author Luke Lindsay
*/
public class LineDrawTrackPieceView implements
jfreerails.client.renderer.TrackPieceRenderer {
private int[] xx = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };
private int[] yy = { -1, -1, -1, 0, 0, 0, 1, 1, 1 };
public java.awt.Image getTrackPieceIcon(int trackTemplate) {
return null;
}
public void drawTrackPieceIcon(int trackTemplate, java.awt.Graphics g,
int x, int y, java.awt.Dimension tileSize) {
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new java.awt.BasicStroke(8.0f));
g2.setColor(java.awt.Color.red);
if (0 != trackTemplate) {
int drawX = x * tileSize.width;
int drawY = y * tileSize.height;
// g.drawLine(drawX-10,drawY-10,drawX+10,drawY+10);
for (int i = 0; i < 9; i++) {
if ((trackTemplate & (1 << i)) == (1 << i)) {
g2.drawLine(drawX + 15, drawY + 15,
drawX + 15 + 15 * xx[i], drawY + 15 + 15 * yy[i]);
}
}
}
}
public void dumpImages(ImageManager imageManager) {
// TODO Auto-generated method stub
}
}
Methods:
MethodJavadoc
drawTrackPieceIcon
dumpImages
getTrackPieceIcon
experimental.RunMe
Javadoc:
/** * Tests that ClientJFrame and ScreenHandler work together. * * @author Luke Lindsay */
Source code:
/**
* Tests that ClientJFrame and ScreenHandler work together.
*
* @author Luke Lindsay
*/
public class RunMe {
public static void main(String[] args) {
JFrame jFrame = new jfreerails.client.top.ClientJFrame(
new SimpleComponentFactoryImpl2());
// jFrame.show();
ScreenHandler screenHandler = new ScreenHandler(jFrame,
ScreenHandler.WINDOWED_MODE);
GameLoop gameLoop = new GameLoop(screenHandler);
Thread t = new Thread(gameLoop);
t.start();
}
}
Methods:
MethodJavadoc
main
experimental.SimpleComponentFactoryImpl2
Javadoc:
/** * This GUIComponentFactory creates simple components that can be used to test * the layout of the client jFrame without running the whole game. * * @author Luke Lindsay */
Source code:
/**
* This GUIComponentFactory creates simple components that can be used to test
* the layout of the client jFrame without running the whole game.
*
* @author Luke Lindsay
*/
public class SimpleComponentFactoryImpl2 implements
jfreerails.client.top.GUIComponentFactory {
private OverviewMapJComponent overviewMap;
private JScrollPane mainMapScrollPane1;
private MapViewJComponentConcrete mainMap;
private MainMapAndOverviewMapMediator mediator;
private Rectangle r = new Rectangle();
/** Creates new SimpleComponentFactoryImpl */
public SimpleComponentFactoryImpl2() {
}
public JMenu createBuildMenu() {
return new JMenu("Build");
}
public JMenu createGameMenu() {
return new JMenu("Game");
}
public JMenu createDisplayMenu() {
JMenu displayMenu = new JMenu("Display");
addMainmapzoomMenuItem(displayMenu, 5);
addMainmapzoomMenuItem(displayMenu, 10);
addOverviewmapzoomMenuItem(displayMenu, 0.2F);
addOverviewmapzoomMenuItem(displayMenu, 0.6F);
return displayMenu;
}
public JMenu createBrokerMenu() {
JMenu brokerMenu = new JMenu("Broker");
return brokerMenu;
}
private void addOverviewmapzoomMenuItem(JMenu displayMenu, final float scale) {
String menuItemName = "Set overview map scale=" + scale;
JMenuItem menuItem = new JMenuItem(menuItemName);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
overviewMap.setup(new BlankMapRenderer(scale));
}
});
displayMenu.add(menuItem);
}
private void addMainmapzoomMenuItem(JMenu displayMenu, final float scale) {
String menuItemName = "Set main map scale=" + scale;
JMenuItem menuItem = new JMenuItem(menuItemName);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Rectangle visRect = mainMap.getVisibleRect();
int oldWidth = mainMap.getWidth();
mainMap.setup(new BlankMapRenderer(scale));
int newWidth = mainMap.getPreferredSize().width;
int oldCenterX = visRect.x + (visRect.width / 2);
int newCenterX = oldCenterX * newWidth / oldWidth;
visRect.x = newCenterX - visRect.width / 2;
int oldCenterY = visRect.y + (visRect.height / 2);
int newCenterY = oldCenterY * newWidth / oldWidth;
visRect.y = newCenterY - visRect.height / 2;
/*
* LL: I'm not sure why the 'if' is necessary in the following,
* but the view does not center on the right spot without it.
*/
if (oldWidth < newWidth) {
mainMap.setSize(mainMap.getPreferredSize());
mainMap.scrollRectToVisible(visRect);
} else {
mainMap.scrollRectToVisible(visRect);
mainMap.setSize(mainMap.getPreferredSize());
}
}
});
displayMenu.add(menuItem);
}
public JScrollPane createMainMap() {
if (null == this.mainMap) {
// this.mainMap = new MapJPanel();
this.mainMap = new MapViewJComponentConcrete();
mainMapScrollPane1 = new JScrollPane();
mainMapScrollPane1.setViewportView(this.mainMap);
addMainMapAndOverviewMapMediatorIfNecessary();
}
return mainMapScrollPane1;
}
public JPanel createOverviewMap() {
if (null == this.overviewMap) {
// this.overviewMap = new OverviewMapJPanel();
this.overviewMap = new OverviewMapJComponent(r);
this.overviewMap.setup(new BlankMapRenderer(0.4F));
addMainMapAndOverviewMapMediatorIfNecessary();
}
return overviewMap;
// return new TestPanel();
}
private void addMainMapAndOverviewMapMediatorIfNecessary() {
if (this.mainMap != null && this.overviewMap != null
&& null == this.mediator) {
// Rectangle r = this.overviewMap.getMainMapVisibleRect();
this.mediator = new MainMapAndOverviewMapMediator(overviewMap,
mainMapScrollPane1.getViewport(), mainMap, r);
}
}
public JLabel createCashJLabel() {
return null;
}
public JLabel createDateJLabel() {
return null;
}
public JMenu createHelpMenu() {
return null;
}
public JTabbedPane createTrainsJTabPane() {
return null;
}
public JMenu createReportsMenu() {
// TODO Auto-generated method stub
return null;
}
}
Methods:
MethodJavadoc
addMainMapAndOverviewMapMediatorIfNecessary
addMainmapzoomMenuItem
addOverviewmapzoomMenuItem
createBrokerMenu
createBuildMenu
createCashJLabel
createDateJLabel
createDisplayMenu
createGameMenu
createHelpMenu
createMainMap
createOverviewMap
createReportsMenu
createTrainsJTabPane
experimental.SimpleMoveReceiver
Javadoc:
/** * An UntriedMoveReceiver that executes moves on the world object passed to its * constructor. * * @author Luke * */
Source code:
/**
* An UntriedMoveReceiver that executes moves on the world object passed to its
* constructor.
*
* @author Luke
*
*/
public final class SimpleMoveReceiver implements UntriedMoveReceiver {
private final World w;
public SimpleMoveReceiver(World w) {
this.w = w;
if (null == w)
throw new NullPointerException();
}
public MoveStatus tryDoMove(Move move) {
return move.tryDoMove(w, Player.AUTHORITATIVE);
}
public void processMove(Move move) {
move.doMove(w, Player.AUTHORITATIVE);
}
public void processPreMove(PreMove pm) {
processMove(pm.generateMove(w));
}
}
Methods:
MethodJavadoc
processMove
processPreMove
tryDoMove
experimental.TestLogging
Javadoc:
/** * <p> * Used to test the logging configuration. * </p> * <p> * Usage:<code> java -Djava.util.logging.config.file=logging.properties experimental.TestLogging</code> * </p> * <p> * Make sure <code>logging.properties</code> is in the working directory. * </p> * * @author Luke */
Source code:
/**
* <p>
* Used to test the logging configuration.
* </p>
* <p>
* Usage:<code> java -Djava.util.logging.config.file=logging.properties experimental.TestLogging</code>
* </p>
* <p>
* Make sure <code>logging.properties</code> is in the working directory.
* </p>
*
* @author Luke
*/
public class TestLogging {
public static void main(String[] args) {
Logger logger1 = Logger.getLogger(TestLogging.class.getName());
logger1.info("Logging properties file: "
+ System.getProperty("java.util.logging.config.file"));
logger1.severe("Hello severe logging");
logger1.warning("Hello warning logging");
logger1.info("Hello info logging");
logger1.fine("Hello fine logging");
logger1.finer("Hello finer logging");
logger1.finest("Hello finest logging");
}
}
Methods:
MethodJavadoc
main
experimental.TrackRenderer
Javadoc:
/** * Provides methods that render track pieces. * * @see experimental.TrackTilesGenerator * @author Luke Lindsay * */
Source code:
/**
* Provides methods that render track pieces.
*
* @see experimental.TrackTilesGenerator
* @author Luke Lindsay
*
*/
public class TrackRenderer {
private final ImageManager imageManager = new ImageManagerImpl(
"/jfreerails/client/graphics/");
Color sleepersColor = new Color(118, 54, 36);
Color railsColor = new Color(118, 118, 118);
double sleeperLength = 6;
float sleeperWidth = 2f;
float targetSleeperGap = 2.5f;
float tileWidth = 30f;
float gauge = 3f;
BasicStroke rail = new BasicStroke(1f);
boolean doubleTrack = false;
float doubleTrackGap = 4f;
Image icon = null;
boolean tunnel = false;
void paintTrackConf(Graphics2D g2, TrackConfiguration conf) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Draw title
// String title = BinaryNumberFormatter.formatWithLowBitOnLeft(conf
// .get9bitTemplate(), 9);
// g.setColor(Color.BLACK);
// g.setFont(font);
//
// g.drawString(title, 10, 10);
Step[] directions = Step.getList();
List<CubicCurve2D.Double> sections = new ArrayList<CubicCurve2D.Double>();
int matches = 0;
for (int i = 0; i < directions.length - 2; i++) {
if (conf.contains(directions[i])) {
// System.out.println("\n"+directions[i]+" to ..");
int maxJ = Math.min(i + 7, directions.length);
for (int j = i + 2; j < maxJ; j++) {
// System.out.println(directions[j]);
if (conf.contains(directions[j])) {
Double toCurve = toCurve(directions[i], directions[j]);
if (doubleTrack) {
sections.add(createAdjacentCurve(toCurve,
doubleTrackGap, doubleTrackGap));
sections.add(createAdjacentCurve(toCurve,
-doubleTrackGap, -doubleTrackGap));
} else {
sections.add(toCurve);
}
matches++;
}
}
}
}
if (matches == 0) {
for (int i = 0; i < directions.length; i++) {
if (conf.contains(directions[i])) {
Double toCurve = toCurve(directions[i]);
if (doubleTrack) {
sections.add(createAdjacentCurve(toCurve,
doubleTrackGap, doubleTrackGap));
sections.add(createAdjacentCurve(toCurve,
-doubleTrackGap, -doubleTrackGap));
} else {
sections.add(toCurve);
}
}
}
}
paintTrack(g2, sections);
}
CubicCurve2D.Double toCurve(Step a) {
float halfTile = tileWidth / 2;
Point2D.Double start, end, one;
start = new Point2D.Double();
start.x = tileWidth + (halfTile * a.deltaX);
start.y = tileWidth + (halfTile * a.deltaY);
one = controlPoint(start);
end = new Point2D.Double(tileWidth, tileWidth);
CubicCurve2D.Double returnValue = new CubicCurve2D.Double();
returnValue.setCurve(start, one, one, end);
return returnValue;
}
CubicCurve2D.Double toCurve(Step a, Step b) {
float halfTile = tileWidth / 2;
Point2D.Double start, end, one, two;
start = new Point2D.Double();
start.x = tileWidth + (halfTile * a.deltaX);
start.y = tileWidth + (halfTile * a.deltaY);
one = controlPoint(start);
end = new Point2D.Double();
end.x = tileWidth + (halfTile * b.deltaX);
end.y = tileWidth + (halfTile * b.deltaY);
two = controlPoint(end);
CubicCurve2D.Double returnValue = new CubicCurve2D.Double();
returnValue.setCurve(start, one, two, end);
return returnValue;
}
void paintTrack(Graphics2D g, List<CubicCurve2D.Double> sections) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if (!tunnel) {
// Draw sleepers
g.setColor(sleepersColor);
for (CubicCurve2D.Double section : sections) {
BasicStroke dashed = getStroke4Curve(section);
g.setStroke(dashed);
g.draw(section);
}
g.setColor(railsColor);
} else {
g.setColor(Color.BLACK);
}
// Draw rails
g.setStroke(rail);
for (CubicCurve2D.Double section : sections) {
float halfGauge = gauge / 2;
CubicCurve2D.Double rail1 = createAdjacentCurve(section, halfGauge,
halfGauge);
CubicCurve2D.Double rail2 = createAdjacentCurve(section,
-halfGauge, -halfGauge);
g.draw(rail1);
g.draw(rail2);
}
}
/**
* Generates the Stroke used to draw the sleepers for track section
* represented by the specified curve.
*/
public BasicStroke getStroke4Curve(CubicCurve2D.Double curve) {
PathIterator fpt = curve.getPathIterator(new AffineTransform(), 0.01);
double length = 0;
double[] coords = new double[6];
double x, y;
fpt.currentSegment(coords);
double lastX = coords[0];
double lastY = coords[1];
for (; !fpt.isDone(); fpt.next()) {
fpt.currentSegment(coords);
x = coords[0];
y = coords[1];
double dx = x - lastX;
double dy = y - lastY;
length += Math.sqrt(dx * dx + dy * dy);
lastX = x;
lastY = y;
}
float sleepers = (float) length / (targetSleeperGap + sleeperWidth);
float sleeperCount = (int) sleepers;
float sleeperGap = (float) length / sleeperCount - sleeperWidth;
float dash1[] = { sleeperWidth, sleeperGap };
float phase = sleeperWidth + (sleeperGap / 2);
return new BasicStroke((float) sleeperLength, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, dash1, phase);
}
public static Line2D.Double createParallelLine(Line2D.Double line,
double shift) {
Line2D.Double returnValue = new Line2D.Double(line.getP1(), line
.getP2());
double distance = line.getP1().distance(line.getP2());
double dRatio = shift / distance;
double dx = (line.x1 - line.x2) * dRatio;
double dy = (line.y1 - line.y2) * dRatio;
returnValue.x1 -= dy;
returnValue.y1 += dx;
returnValue.x2 -= dy;
returnValue.y2 += dx;
return returnValue;
}
public static CubicCurve2D.Double createAdjacentCurve(
CubicCurve2D.Double c, double shift1, double shift2) {
Line2D.Double line1 = new Line2D.Double(c.getX1(), c.getY1(), c
.getCtrlX1(), c.getCtrlY1());
Line2D.Double line2 = new Line2D.Double(c.getX2(), c.getY2(), c
.getCtrlX2(), c.getCtrlY2());
line1 = createParallelLine(line1, shift1);
line2 = createParallelLine(line2, -shift2);
return new CubicCurve2D.Double(line1.x1, line1.y1, line1.x2, line1.y2,
line2.x2, line2.y2, line2.x1, line2.y1);
}
private Point2D.Double controlPoint(Point2D.Double from) {
double weight = 0.3;
double x = from.getX() * weight + tileWidth * (1 - weight);
double y = from.getY() * weight + tileWidth * (1 - weight);
return new Point2D.Double(x, y);
}
void setIcon(String typeName) {
try {
String relativeFileName = "icons" + File.separator + typeName
+ ".png";
relativeFileName = relativeFileName.replace(' ', '_');
Image im = imageManager.getImage(relativeFileName);
icon = im;
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException(e);
}
}
}
Methods:
MethodJavadoc
controlPoint/**
createAdjacentCurve
createParallelLine
getStroke4Curve/**
paintTrack
paintTrackConf
setIcon
toCurve
toCurve
experimental.TrackTilesGenerator
Javadoc:
/** * Generates track graphic image files. * * @author Luke */
Source code:
/**
* Generates track graphic image files.
*
* @author Luke
*/
public class TrackTilesGenerator extends JPanel {
private static final long serialVersionUID = 3618982273966487859L;
public static void main(String[] args) {
JFrame frame = new JFrame();
JScrollPane scrollPane = new JScrollPane();
frame.add(scrollPane);
TrackTilesGenerator trackTilesGenerator = new TrackTilesGenerator();
trackTilesGenerator.setPreferredSize(trackTilesGenerator
.getSize4Panel());
scrollPane.setViewportView(trackTilesGenerator);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private final ImageManager imageManager = new ImageManagerImpl(
"/experimental/", "/experimental/");
private List<TrackRule> rules;
private TrackRenderer tr;
CubicCurve2D.Double[] track;
public TrackTilesGenerator() {
Point2D.Double start, end, one, two;
track = new CubicCurve2D.Double[3];
track[0] = new CubicCurve2D.Double();
start = new Point2D.Double(150, 300);
end = new Point2D.Double(450, 150);
one = controlPoint(start);
two = controlPoint(end);
track[0].setCurve(start, one, two, end);
track[1] = TrackRenderer.createAdjacentCurve(track[0], 0, 0);
track[2] = TrackRenderer.createAdjacentCurve(track[0], -60, -60);
tr = new TrackRenderer();
URL track_xml_url = OldWorldImpl.class
.getResource("/jfreerails/data/track_tiles.xml");
Track_TilesHandlerImpl trackSetFactory = new Track_TilesHandlerImpl(
track_xml_url);
rules = trackSetFactory.getRuleList();
generateTiles();
}
private Point2D.Double controlPoint(Point2D.Double from) {
double weight = 0.3;
double x = from.getX() * weight + 300 * (1 - weight);
double y = from.getY() * weight + 300 * (1 - weight);
return new Point2D.Double(x, y);
}
private void generateTiles() {
for (TrackRule rule : rules) {
TrackRule.TrackCategories category = rule.getCategory();
Image icon;
if (category.equals(TrackRule.TrackCategories.bridge)
|| category.equals(TrackRule.TrackCategories.station)) {
tr.setIcon(rule.getTypeName());
icon = tr.icon;
} else {
icon = null;
}
if (category.equals(TrackRule.TrackCategories.tunnel)) {
tr.tunnel = true;
} else {
tr.tunnel = false;
}
tr.doubleTrack = rule.isDouble();
for (int i = 0; i < 512; i++) {
if (rule.testTrackPieceLegality(i)) {
String fileName = TrackPieceRendererImpl.generateFilename(
i, rule.getTypeName());
TrackConfiguration conf = TrackConfiguration
.from9bitTemplate(i);
Image smallImage = imageManager.newBlankImage(60, 60);
Graphics2D g2 = (Graphics2D) smallImage.getGraphics();
tr.paintTrackConf(g2, conf);
// Draw icon. Used for bridges and stations.
if (null != icon) {
int x = 30 - icon.getWidth(null) / 2;
int y = 30 - icon.getHeight(null) / 2;
g2.drawImage(icon, x, y, null);
}
g2.dispose();
imageManager.setImage(fileName, smallImage);
}
}
}
try {
imageManager.writeAllImages();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Dimension getSize4Panel() {
int height = 90 * rules.size();
int width = 0;
int lastWidth = 0;
for (TrackRule rule : rules) {
width = Math.max(width, lastWidth);
lastWidth = 0;
Iterator<TrackConfiguration> it = rule
.getLegalConfigurationsIterator();
while (it.hasNext()) {
lastWidth += 60;
}
}
return new Dimension(width, height);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (TrackRule rule : rules) {
String typeName = rule.getTypeName();
typeName += rule.isDouble() ? " (Double) " : " (Single)";
g.drawString(typeName, 10, 10);
g.translate(0, 30);
Graphics2D g2 = (Graphics2D) g.create();
for (int i = 0; i < 512; i++) {
if (rule.testTrackPieceLegality(i)) {
String fileName = TrackPieceRendererImpl.generateFilename(
i, rule.getTypeName());
Image tile;
try {
tile = imageManager.getImage(fileName);
g2.drawImage(tile, 0, 0, null);
g2.translate(60, 0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
g.translate(0, 60);
}
}
}
Methods:
MethodJavadoc
controlPoint
generateTiles
getSize4Panel
main
paintComponent
experimental.TrainMotionExpt
Javadoc:
/** * This class is a visual test for the train movement code. * * TODO: Update the trains position when necessary. Make the train stop at * intervals, and slowly accelerate. * * @author Luke Lindsay * */
Source code:
/**
* This class is a visual test for the train movement code.
*
* TODO: Update the trains position when necessary. Make the train stop at
* intervals, and slowly accelerate.
*
* @author Luke Lindsay
*
*/
public class TrainMotionExpt extends JComponent {
private static final long serialVersionUID = 3690191057862473264L;
private final World world;
private final FreerailsPrincipal principal;
private double finishTime = 0;
private long startTime;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Shade tiles with track..
g.setColor(Color.GREEN);
for (int x = 0; x < world.getMapWidth(); x++) {
for (int y = 0; y < world.getMapHeight(); y++) {
FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
if (tile.getTrackPiece().getTrackTypeID() != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
int w = Step.TILE_DIAMETER;
int h = Step.TILE_DIAMETER;
g.drawRect(x * Step.TILE_DIAMETER, y * Step.TILE_DIAMETER,
w, h);
}
}
}
long l = System.currentTimeMillis() - startTime;
double ticks = (double) l / 1000;
while (ticks > finishTime) {
updateTrainPosition();
}
ActivityIterator ai = world.getActivities(principal, 0);
while (ai.getFinishTime() < ticks && ai.hasNext()) {
ai.nextActivity();
}
double t = Math.min(ticks, ai.getFinishTime());
t = t - ai.getStartTime();
TrainMotion motion = (TrainMotion) ai.getActivity();
TrainPositionOnMap pos = (TrainPositionOnMap) ai.getState(ticks);
PathOnTiles pathOT = motion.getPath();
Iterator<ImPoint> it = pathOT.tiles();
while (it.hasNext()) {
ImPoint tile = it.next();
int x = tile.x * Step.TILE_DIAMETER;
int y = tile.y * Step.TILE_DIAMETER;
int w = Step.TILE_DIAMETER;
int h = Step.TILE_DIAMETER;
g.setColor(Color.WHITE);
g.fillRect(x, y, w, h);
g.setColor(Color.DARK_GRAY);
g.drawRect(x, y, w, h);
}
pathOT = motion.getTiles(t);
it = pathOT.tiles();
while (it.hasNext()) {
ImPoint tile = it.next();
int x = tile.x * Step.TILE_DIAMETER;
int y = tile.y * Step.TILE_DIAMETER;
int w = Step.TILE_DIAMETER;
int h = Step.TILE_DIAMETER;
g.setColor(Color.LIGHT_GRAY);
g.fillRect(x, y, w, h);
g.setColor(Color.DARK_GRAY);
g.drawRect(x, y, w, h);
}
g.setColor(Color.BLACK);
IntLine line = new IntLine();
FreerailsPathIterator path = pos.path();
while (path.hasNext()) {
path.nextSegment(line);
g.drawLine(line.x1, line.y1, line.x2, line.y2);
}
int speed = (int) Math.round(pos.getSpeed());
g.drawString("Speed: " + speed, 260, 60);
}
private void updateTrainPosition() {
Random rand = new Random(System.currentTimeMillis());
MoveTrainPreMove moveTrain = new MoveTrainPreMove(0, principal);
Move m;
if (rand.nextInt(10) == 0) {
m = moveTrain.stopTrain(world);
} else {
m = moveTrain.generateMove(world);
}
MoveStatus ms = m.doMove(world, principal);
if (!ms.ok)
throw new IllegalStateException(ms.message);
ActivityIterator ai = world.getActivities(principal, 0);
while (ai.hasNext()) {
ai.nextActivity();
finishTime = ai.getFinishTime();
}
}
public TrainMotionExpt() {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
TrackMoveProducer producer = new TrackMoveProducer(me, world, mr);
Step[] trackPath = { EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, WEST,
NORTH_WEST, NORTH, NORTH_EAST };
ImPoint from = new ImPoint(5, 5);
MoveStatus ms = producer.buildTrack(from, trackPath);
if (!ms.ok)
throw new IllegalStateException(ms.message);
TrainOrdersModel[] orders = {};
ImmutableSchedule is = new ImmutableSchedule(orders, -1, false);
AddTrainPreMove addTrain = new AddTrainPreMove(0, new ImInts(), from,
principal, is);
Move m = addTrain.generateMove(world);
ms = m.doMove(world, principal);
if (!ms.ok)
throw new IllegalStateException(ms.message);
startTime = System.currentTimeMillis();
}
public static void main(String[] args) {
System.setProperty("SHOWFPS", "true");
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.getContentPane().add(new TrainMotionExpt());
ScreenHandler screenHandler = new ScreenHandler(f,
ScreenHandler.WINDOWED_MODE);
screenHandler.apply();
GameLoop gameLoop = new GameLoop(screenHandler);
Thread t = new Thread(gameLoop);
t.start();
}
}
Methods:
MethodJavadoc
main
paintComponent
updateTrainPosition
jfreerails.JavaDocPlaceholder
Javadoc:
/** * This class does nothing and is only here so that javadoc gets generated * correctly. * * @author Luke * */
Source code:
/**
* This class does nothing and is only here so that javadoc gets generated
* correctly.
*
* @author Luke
*
*/
public class JavaDocPlaceholder {
}
No methods in this class.
jfreerails.client.common.ActionAdapter
Javadoc:
/** * Provides a mapping from a set of ButtonModels or a ComboBoxModel to a set of * Actions. To use with a set of buttons, call elements() to obtain the set of * ButtonModels to apply to the buttons, and add each button in the enumeration * to a ButtonGroup. Listeners should listen for changes to the model and not to * any events from UI components, although UI components may call setAction() in * order to receive property change updates and to set icons etc. * * @author Rob */
Source code:
/**
* Provides a mapping from a set of ButtonModels or a ComboBoxModel to a set of
* Actions. To use with a set of buttons, call elements() to obtain the set of
* ButtonModels to apply to the buttons, and add each button in the enumeration
* to a ButtonGroup. Listeners should listen for changes to the model and not to
* any events from UI components, although UI components may call setAction() in
* order to receive property change updates and to set icons etc.
*
* @author Rob
*/
public class ActionAdapter extends DefaultComboBoxModel {
private static final long serialVersionUID = 3546920294666351415L;
/**
* The set of actions which each button / menu item correspond to.
*/
private final Action[] actions;
private boolean initialised = false;
private boolean performActionOnSetSelectedItem = true;
/**
* The set of MappedButtonModels corresponding to the actions.
*/
private final Vector<MappedButtonModel> buttonModels;
/**
* An array of the actions to be used. The ComboBoxModel objects are taken
* from the NAME property of the Action. The ButtonModel icons are obtained
* from the SMALL_ICON property.
*/
public ActionAdapter(Action[] actions) {
super();
this.actions = actions;
buttonModels = new Vector<MappedButtonModel>();
for (int i = 0; i < actions.length; i++) {
buttonModels.add(new MappedButtonModel(actions[i]));
addElement(actions[i].getValue(Action.NAME));
}
initialised = true;
}
/**
* @param actions
* An array of the actions to be used. The ComboBoxModel objects
* are taken from the NAME property of the Action. The
* ButtonModel icons are obtained from the SMALL_ICON property.
* @param selected
* Index of the default selected action.
*/
public ActionAdapter(Action[] actions, int selected) {
this(actions);
for (int i = 0; i < buttonModels.size(); i++) {
MappedButtonModel bm = buttonModels.get(i);
bm.setSelected(i == selected);
}
}
/**
* @return an enumeration of Action
*/
public Enumeration<Action> getActions() {
return new Enumeration<Action>() {
private int i = 0;
public boolean hasMoreElements() {
return (i < actions.length);
}
public Action nextElement() {
return actions[i++];
}
};
}
/**
* @return an enumeration of MappedButtonModel
*/
public Enumeration<MappedButtonModel> getButtonModels() {
return buttonModels.elements();
}
/**
* @param item
* The NAME of the Action selected
*/
@Override
public void setSelectedItem(Object item) {
// only set the item if not already selected
if ((item != null) && item.equals(getSelectedItem())) {
return;
}
super.setSelectedItem(item);
// stop addElement from triggering actions
if (!initialised) {
return;
}
for (int i = 0; i < buttonModels.size(); i++) {
MappedButtonModel bm = buttonModels.get(i);
if (bm.actionName.equals(item)) {
bm.setSelected(true);
}
}
if (performActionOnSetSelectedItem) {
for (int i = 0; i < actions.length; i++) {
if (actions[i].getValue(Action.NAME).equals(item)) {
actions[i].actionPerformed(new ActionEvent(this,
ActionEvent.ACTION_PERFORMED, (String) actions[i]
.getValue(Action.ACTION_COMMAND_KEY)));
}
}
}
}
public class MappedButtonModel extends JToggleButton.ToggleButtonModel
implements PropertyChangeListener {
private static final long serialVersionUID = 3834589889856353845L;
/**
* The NAME of the Action to which this ButtonModel is mapped.
*/
public final String actionName;
public MappedButtonModel(Action action) {
actionName = (String) action.getValue(Action.NAME);
action.addPropertyChangeListener(this);
setEnabled(action.isEnabled());
}
@Override
public void setSelected(boolean b) {
if (isSelected() != b) {
super.setSelected(b);
if (b) {
ActionAdapter.this.setSelectedItem(actionName);
}
}
}
public void propertyChange(PropertyChangeEvent e) {
setEnabled(((Action) e.getSource()).isEnabled());
}
}
public void setPerformActionOnSetSelectedItem(
boolean performActionOnSetSelectedItem) {
this.performActionOnSetSelectedItem = performActionOnSetSelectedItem;
}
}
Methods:
MethodJavadoc
getActions/**
getButtonModels/**
setPerformActionOnSetSelectedItem
setSelectedItem/**
jfreerails.client.common.BinaryNumberFormatter
Javadoc:
/** * Used to generate filenames for track and terrain images. * * @author Luke */
Source code:
/**
* Used to generate filenames for track and terrain images.
*
* @author Luke
*/
public class BinaryNumberFormatter {
public static String format(int i, int bits) {
int maxValue = 1 << (bits);
if (i < 0) {
throw new IllegalArgumentException(
"i must be greater than 0. It was " + i);
}
if (i >= maxValue) {
throw new IllegalArgumentException("i must be less than "
+ maxValue + ". It was " + i);
}
String s = Integer.toString(i + maxValue, 2);
String number = s.substring(1);
return number;
}
public static String formatWithLowBitOnLeft(int i, int bits) {
StringBuffer buff = new StringBuffer(format(i, bits));
buff.reverse();
return buff.toString();
}
}
Methods:
MethodJavadoc
format
formatWithLowBitOnLeft
jfreerails.client.common.ImageManager
Javadoc:
/** * This interface defines methods for loading and saving images, and producing * scaled images whose quality may be controlled. * * @author Luke * */
Source code:
/**
* This interface defines methods for loading and saving images, and producing
* scaled images whose quality may be controlled.
*
* @author Luke
*
*/
public interface ImageManager {
Image newBlankImage(int height, int width);
void setPathToReadFrom(String s);
void setPathToWriteTo(String s);
Image getImage(String relativeFilename) throws IOException;
boolean contains(String relativeFilename);
void setImage(String relativeFilename, Image i);
void writeImage(String relativeFilename) throws IOException;
void writeAllImages() throws IOException;
Image getScaledImage(String relativeFilename, int height)
throws IOException;
}
Methods:
MethodJavadoc
contains
getImage
getScaledImage
newBlankImage
setImage
setPathToReadFrom
setPathToWriteTo
writeAllImages
writeImage
jfreerails.client.common.ImageManagerImpl
Javadoc:
/** * Implementation of ImageManager that returns images that are compatible with * the current graphics configuration and whose transparency is set to * TRANSLUCENT, the scaled images it returns are rendered with renderingHints * set for quality. * * @author Luke * */
Source code:
/**
* Implementation of ImageManager that returns images that are compatible with
* the current graphics configuration and whose transparency is set to
* TRANSLUCENT, the scaled images it returns are rendered with renderingHints
* set for quality.
*
* @author Luke
*
*/
public class ImageManagerImpl implements ImageManager {
/**
* Matches anying but a string beginning with a "/"*. The reason for this
* check is that relative filenames such as "/cursor/removetrack.png" work
* from with files but not from within jars, which lets bugs slip in.
*/
private static final String A_REGEX = "^[^///].*";
private static final Logger logger = Logger
.getLogger(ImageManagerImpl.class.getName());
private static final Pattern pattern = Pattern.compile(A_REGEX);
public static boolean isValid(String s) {
Matcher m = pattern.matcher(s);
return m.matches();
}
private final GraphicsConfiguration defaultConfiguration = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
private final HashMap<String, Image> imageHashMap = new HashMap<String, Image>();
private String pathToReadFrom;
private String pathToWriteTo;
private final RenderingHints renderingHints;
private final HashMap<String, Image> scaledImagesHashMap = new HashMap<String, Image>();
public ImageManagerImpl(String readpath) {
this(readpath, null);
}
public ImageManagerImpl(String readpath, String writePath) {
pathToReadFrom = readpath;
pathToWriteTo = writePath;
// Attempt to increase quality..
renderingHints = new RenderingHints(
RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
renderingHints.put(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
renderingHints.put(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
}
public boolean contains(String relativeFilename) {
relativeFilename = relativeFilename.replace(' ', '_');
if (imageHashMap.containsKey(relativeFilename)) {
return true;
}
File f = new File(pathToWriteTo + File.separator + relativeFilename);
if (f.isFile()) {
return true;
}
return false;
}
public Image getImage(String relativeFilename) throws IOException {
relativeFilename = relativeFilename.replace(' ', '_');
if (!isValid(relativeFilename))
throw new IllegalArgumentException(relativeFilename
+ " must match " + A_REGEX);
if (imageHashMap.containsKey(relativeFilename)) {
return imageHashMap.get(relativeFilename);
}
// File f = new File(pathToReadFrom+File.separator+relativeFilename);
String read = pathToReadFrom + relativeFilename;
read = read.replace(File.separatorChar, '/');
URL url = ImageManagerImpl.class.getResource(read);
if (null == url) {
throw new IOException("Couldn't find: " + read);
}
Image tempImage = ImageIO.read(url);
if (null == tempImage) {
throw new IOException("Couldn't find: " + read);
}
Image compatibleImage = defaultConfiguration.createCompatibleImage(
tempImage.getWidth(null), tempImage.getHeight(null),
Transparency.TRANSLUCENT);
Graphics g = compatibleImage.getGraphics();
g.drawImage(tempImage, 0, 0, null);
imageHashMap.put(relativeFilename, compatibleImage);
return compatibleImage;
}
/**
* Returns the specified image scaled so that its height is equal to the
* specified height.
*/
public Image getScaledImage(String relativeFilename, int height)
throws IOException {
relativeFilename = relativeFilename.replace(' ', '_');
if (!isValid(relativeFilename))
throw new IllegalArgumentException(relativeFilename
+ " must match " + A_REGEX);
String hashKey = relativeFilename + height;
if (this.scaledImagesHashMap.containsKey(hashKey)) {
return scaledImagesHashMap.get(hashKey);
}
Image i = getImage(relativeFilename);
if (i.getHeight(null) == height) {
return i;
}
int width = (i.getWidth(null) * height) / i.getHeight(null);
Image compatibleImage = newBlankImage(height, width);
Graphics2D g = (Graphics2D) compatibleImage.getGraphics();
g.setRenderingHints(this.renderingHints);
g.drawImage(i, 0, 0, width, height, null);
scaledImagesHashMap.put(hashKey, compatibleImage);
return compatibleImage;
}
public Image newBlankImage(int height, int width) {
Image compatibleImage = defaultConfiguration.createCompatibleImage(
width, height, Transparency.TRANSLUCENT);
return compatibleImage;
}
public void setImage(String relativeFilename, Image i) {
relativeFilename = relativeFilename.replace(' ', '_');
if (i == null) {
throw new NullPointerException(relativeFilename);
}
imageHashMap.put(relativeFilename, i);
}
public void setPathToReadFrom(String s) {
pathToReadFrom = s;
}
public void setPathToWriteTo(String s) {
pathToWriteTo = s;
}
public void writeAllImages() throws IOException {
for (String s : imageHashMap.keySet()) {
writeImage(s);
}
}
public void writeImage(String relativeFilename) throws IOException {
if (null == pathToWriteTo)
throw new NullPointerException("null == pathToWriteTo");
relativeFilename = relativeFilename.replace(' ', '_');
File f = new File(pathToWriteTo + File.separator + relativeFilename);
if (imageHashMap.containsKey(relativeFilename)) {
RenderedImage i = (RenderedImage) imageHashMap
.get(relativeFilename);
String pathName = f.getPath();
File path = new File(pathName);
path.mkdirs();
ImageIO.write(i, "png", f);
logger.info("Writing " + f);
} else {
throw new NoSuchElementException(relativeFilename);
}
}
}
Methods:
MethodJavadoc
contains
getImage
getScaledImage/**
isValid
newBlankImage
setImage
setPathToReadFrom
setPathToWriteTo
writeAllImages
writeImage
jfreerails.client.common.ModelRootImpl
Javadoc:
/** * Provides access to the World object and other data that is shared by GUI * components (for instance the cursor's position). * * @author Luke * @author Rob */
Source code:
/**
* Provides access to the World object and other data that is shared by GUI
* components (for instance the cursor's position).
*
* @author Luke
* @author Rob
*/
public final class ModelRootImpl implements ModelRoot, ServerCommandReceiver {
public boolean hasBeenSetup = false;
private MoveChainFork moveFork = new MoveChainFork();
private UntriedMoveReceiver moveReceiver = new UntriedMoveReceiver() {
public void processMove(Move Move) {
}
public void processPreMove(PreMove pm) {
}
public MoveStatus tryDoMove(Move move) {
return MoveStatus.moveFailed("No move receiver set on model root!");
}
};
private FreerailsPrincipal playerPrincipal;
private final HashMap<Property, Object> properties = new HashMap<Property, Object>();
private ServerCommandReceiver serverCommandReceiver;
private ReadOnlyWorld world;
private final ArrayList<ModelRootListener> listeners = new ArrayList<ModelRootListener>();
public ModelRootImpl() {
properties.put(Property.CURSOR_POSITION, new ImPoint());
properties.put(Property.SHOW_STATION_NAMES, Boolean.TRUE);
properties.put(Property.SHOW_CARGO_AT_STATIONS, Boolean.TRUE);
properties.put(Property.SHOW_STATION_BORDERS, Boolean.TRUE);
properties.put(Property.CURSOR_MODE, Value.BUILD_TRACK_CURSOR_MODE);
properties.put(Property.PREVIOUS_CURSOR_MODE,
Value.BUILD_TRACK_CURSOR_MODE);
properties.put(Property.SERVER, "server details not set!");
properties.put(Property.PLAY_SOUNDS, Boolean.TRUE);
properties.put(Property.IGNORE_KEY_EVENTS, Boolean.FALSE);
properties.put(Property.TIME, new Double(0));
properties.put(Property.TRACK_BUILDER_MODE,
TrackMoveProducer.BuildMode.BUILD_TRACK);
properties.put(Property.SAVED_GAMES_LIST, new ImStringList());
addPropertyChangeListener(SoundManager.getSoundManager());
}
public void addCompleteMoveReceiver(MoveReceiver l) {
this.moveFork.addCompleteMoveReceiver(l);
}
public void addListListener(WorldListListener listener) {
this.moveFork.addListListener(listener);
}
public void addMapListener(WorldMapListener l) {
this.moveFork.addMapListener(l);
}
public void addPropertyChangeListener(ModelRootListener l) {
listeners.add(l);
}
public void addSplitMoveReceiver(MoveReceiver l) {
this.moveFork.addSplitMoveReceiver(l);
}
public MoveStatus doMove(Move m) {
MoveStatus ms = this.moveReceiver.tryDoMove(m);
this.moveReceiver.processMove(m);
return ms;
}
public MoveStatus doPreMove(PreMove pm) {
Move m = pm.generateMove(world);
MoveStatus ms = moveReceiver.tryDoMove(m);
moveReceiver.processPreMove(pm);
return ms;
}
public FreerailsPrincipal getPrincipal() {
if (null == playerPrincipal) {
throw new NullPointerException();
}
return playerPrincipal;
}
public Object getProperty(Property p) {
return properties.get(p);
}
public ReadOnlyWorld getWorld() {
return world;
}
public void sendCommand(Message2Server c) {
if (null != serverCommandReceiver) {
serverCommandReceiver.sendCommand(c);
} else {
System.err.println(c.toString());
}
}
public void setMoveFork(MoveChainFork moveFork) {
this.moveFork = moveFork;
}
public void setMoveReceiver(UntriedMoveReceiver moveReceiver) {
this.moveReceiver = moveReceiver;
}
public void setProperty(Property p, Object newValue) {
Object oldValue = properties.get(p);
properties.put(p, newValue);
for (ModelRootListener listener : listeners) {
listener.propertyChange(p, oldValue, newValue);
}
}
public void setServerCommandReceiver(
ServerCommandReceiver serverCommandReceiver) {
this.serverCommandReceiver = serverCommandReceiver;
}
/**
* Updates the ModelRoot with those properties which are dependent upon the
* world model. Call this when the world model is changed (e.g. new map is
* loaded)
*/
public void setup(ReadOnlyWorld world, FreerailsPrincipal p) {
this.world = world;
assert p != null;
assert world.isPlayer(p);
playerPrincipal = p;
if (null == world) {
throw new NullPointerException();
}
BuildTrackStrategy bts = BuildTrackStrategy.getDefault(world);
setProperty(ModelRoot.Property.BUILD_TRACK_STRATEGY, bts);
hasBeenSetup = true;
}
public MoveStatus tryDoMove(Move m) {
return this.moveReceiver.tryDoMove(m);
}
public boolean is(ModelRoot.Property p, Object value) {
return getProperty(p).equals(value);
}
}
Methods:
MethodJavadoc
addCompleteMoveReceiver
addListListener
addMapListener
addPropertyChangeListener
addSplitMoveReceiver
doMove
doPreMove
getPrincipal
getProperty
getWorld
is
sendCommand
setMoveFork
setMoveReceiver
setProperty
setServerCommandReceiver
setup/**
tryDoMove
jfreerails.client.common.ModelRootListener
Javadoc:
/** * @author Luke * */
Source code:
/**
* @author Luke
*
*/
public interface ModelRootListener {
void propertyChange(ModelRoot.Property p, Object oldValue, Object newValue);
}
Methods:
MethodJavadoc
propertyChange
jfreerails.client.common.MyGlassPanel
Javadoc:
/** * A transparent JPanel that catches key presses and mouse clicks. * * @author lindsal8 * */
Source code:
/**
* A transparent JPanel that catches key presses and mouse clicks.
*
* @author lindsal8
*
*/
public class MyGlassPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 3976735856986239795L;
public MyGlassPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() { // GEN-BEGIN:initComponents
contentPanel = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
java.awt.GridBagConstraints gridBagConstraints1;
setOpaque(false);
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mousePressed(java.awt.event.MouseEvent evt) {
formMousePressed(evt);
}
});
addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
@Override
public void mouseMoved(java.awt.event.MouseEvent evt) {
formMouseMoved(evt);
}
});
contentPanel.setPreferredSize(new java.awt.Dimension(60, 40));
contentPanel.setMinimumSize(new java.awt.Dimension(60, 40));
contentPanel.setBackground(java.awt.Color.red);
contentPanel.setMaximumSize(new java.awt.Dimension(60, 40));
gridBagConstraints1 = new java.awt.GridBagConstraints();
gridBagConstraints1.gridx = 2;
gridBagConstraints1.gridy = 1;
add(contentPanel, gridBagConstraints1);
}
// GEN-END:initComponents
private void formMouseMoved(java.awt.event.MouseEvent evt) { // GEN-FIRST:event_formMouseMoved
// Add your handling code here:
}
// GEN-LAST:event_formMouseMoved
private void formMousePressed(java.awt.event.MouseEvent evt) { // GEN-FIRST:event_formMousePressed
// Add your handling code here:
}
// GEN-LAST:event_formMousePressed
private void formKeyPressed(java.awt.event.KeyEvent evt) { // GEN-FIRST:event_formKeyPressed
// Add your handling code here:
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComponent contentPanel;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
formKeyPressed
formMouseMoved
formMousePressed
initComponents/**
jfreerails.client.common.Painter
Javadoc:
/** * Paints a layer of the map view. * * @author Luke */
Source code:
/**
* Paints a layer of the map view.
*
* @author Luke
*/
public interface Painter {
void paint(Graphics2D g);
}
Methods:
MethodJavadoc
paint
jfreerails.client.common.RepaintManagerForActiveRendering
Javadoc:
/** * This RepaintManager is intended to be used when we are using active rendering * to paint a top level component. Repaint requests for components whose * TopLevelAncestor is the component being actively rendered in the game loop * are ignored; repaint requests for components whose TopLevelAncestor is * <strong>not</strong> the component being actively rendered in the game loop * are processed normally. This behaviour is needed because when menus extend * outside the bounds of their parent window, they have a different top level * component to the parent window, so are not painted when paintComponents is * called from the game loop. * * @author Luke * */
Source code:
/**
* This RepaintManager is intended to be used when we are using active rendering
* to paint a top level component. Repaint requests for components whose
* TopLevelAncestor is the component being actively rendered in the game loop
* are ignored; repaint requests for components whose TopLevelAncestor is
* <strong>not</strong> the component being actively rendered in the game loop
* are processed normally. This behaviour is needed because when menus extend
* outside the bounds of their parent window, they have a different top level
* component to the parent window, so are not painted when paintComponents is
* called from the game loop.
*
* @author Luke
*
*/
public final class RepaintManagerForActiveRendering extends RepaintManager {
/** The JFrame(s) that are being actively rendered in the game loop(s). */
private static final HashSet<JFrame> activelyRenderedComponents = new HashSet<JFrame>();
private static final RepaintManagerForActiveRendering instance = new RepaintManagerForActiveRendering();
private static long numRepaintRequests = 0;
public static void setAsCurrentManager() {
RepaintManager.setCurrentManager(instance);
}
private RepaintManagerForActiveRendering() {
}
@Override
public synchronized void addDirtyRegion(JComponent c, int x, int y, int w,
int h) {
if (hasDifferentAncestor(c)) {
super.addDirtyRegion(c, x, y, w, h);
} else {
numRepaintRequests++;
}
}
public static synchronized void addJFrame(JFrame f) {
activelyRenderedComponents.add(f);
}
@Override
public synchronized void addInvalidComponent(JComponent invalidComponent) {
if (hasDifferentAncestor(invalidComponent)) {
super.addInvalidComponent(invalidComponent);
} else {
numRepaintRequests++;
}
}
@Override
public void markCompletelyClean(JComponent aComponent) {
if (hasDifferentAncestor(aComponent)) {
super.markCompletelyClean(aComponent);
} else {
numRepaintRequests++;
}
}
@Override
public void markCompletelyDirty(JComponent aComponent) {
if (hasDifferentAncestor(aComponent)) {
super.markCompletelyDirty(aComponent);
} else {
numRepaintRequests++;
}
}
private boolean hasDifferentAncestor(JComponent aComponent) {
Container topLevelAncestor = aComponent.getTopLevelAncestor();
if (null == topLevelAncestor
|| activelyRenderedComponents.contains(topLevelAncestor)) {
return false;
}
return true;
}
public static long getNumRepaintRequests() {
return numRepaintRequests;
}
}
Methods:
MethodJavadoc
addDirtyRegion/**
addInvalidComponent
addJFrame
getNumRepaintRequests
hasDifferentAncestor
markCompletelyClean
markCompletelyDirty
setAsCurrentManager
jfreerails.client.common.SoundManager
Javadoc:
/** * This class is responsible for loading and playing sounds. Samples are read * into a byte arrays so that they don't need to be loaded from disk each time * they are played. * * @author Luke * */
Source code:
/**
* This class is responsible for loading and playing sounds. Samples are read
* into a byte arrays so that they don't need to be loaded from disk each time
* they are played.
*
* @author Luke
*
*/
public class SoundManager implements ModelRootListener, LineListener {
/**
* Stores the audio data and properties of a sample.
*
*/
private static class Sample {
byte[] audio;
AudioFormat format;
DataLine.Info info;
int size;
}
private static final Logger logger = Logger.getLogger(SoundManager.class
.getName());
private static final SoundManager soundManager = new SoundManager();
public static SoundManager getSoundManager() {
return soundManager;
}
public static void main(String[] args) {
SoundManager soundPlayer = getSoundManager();
for (int i = 0; i < 100; i++) {
soundPlayer.playSound("/jfreerails/client/sounds/cash.wav", 10);
try {
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private int maxLines;
private Mixer mixer;
private boolean playSounds = true;
private HashMap<String, Sample> samples = new HashMap<String, Sample>();
private final LinkedList<Clip> voices = new LinkedList<Clip>();
private SoundManager() {
AudioFormat format2 = new AudioFormat(8000f, 16, 1, true, false);
DataLine.Info info2 = new DataLine.Info(Clip.class, format2);
for (Mixer.Info mo : AudioSystem.getMixerInfo()) {
mixer = AudioSystem.getMixer(mo);
maxLines = mixer.getMaxLines(info2);
if (maxLines == AudioSystem.NOT_SPECIFIED){
maxLines = 100;
}
if (maxLines >= 32)
break; // Java Sound Audio Engine, version 1.0 satisfies this.
}
logger.fine("Sound Mixer: " + mixer.getMixerInfo() + "(" + maxLines
+ " voices).");
}
public void addClip(String s) throws IOException,
UnsupportedAudioFileException, LineUnavailableException {
if (samples.containsKey(s)) {
return;
}
URL url = getClass().getResource(s);
AudioInputStream audioInputStream = AudioSystem
.getAudioInputStream(loadStream(url.openStream()));
Sample sample = new Sample();
sample.format = audioInputStream.getFormat();
sample.size = (int) (sample.format.getFrameSize() * audioInputStream
.getFrameLength());
sample.audio = new byte[sample.size];
sample.info = new DataLine.Info(Clip.class, sample.format, sample.size);
audioInputStream.read(sample.audio, 0, sample.size);
samples.put(s, sample);
}
private ByteArrayInputStream loadStream(InputStream inputstream)
throws IOException {
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
for (int i = inputstream.read(data); i != -1; i = inputstream
.read(data)) {
bytearrayoutputstream.write(data, 0, i);
}
inputstream.close();
bytearrayoutputstream.close();
data = bytearrayoutputstream.toByteArray();
return new ByteArrayInputStream(data);
}
public void playSound(String s, int loops) {
if (playSounds) {
try {
if (!samples.containsKey(s)) {
addClip(s);
}
Sample sample = samples.get(s);
Clip clip;
if (voices.size() < maxLines) {
clip = (Clip) mixer.getLine(sample.info);
} else {
clip = voices.removeFirst();
clip.stop();
clip.flush();
clip.close();
}
clip.addLineListener(this);
clip.open(sample.format, sample.audio, 0, sample.size);
clip.loop(loops);
voices.add(clip);
} catch (LineUnavailableException e) {
logger.warning(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void propertyChange(ModelRoot.Property p, Object before, Object after) {
if (p.equals(ModelRoot.Property.PLAY_SOUNDS)) {
Boolean b = (Boolean) after;
playSounds = b.booleanValue();
}
}
public void update(LineEvent event) {
// TODO free up resources when we have finished playing a clip.
}
}
Methods:
MethodJavadoc
addClip
getSoundManager
loadStream
main
playSound
propertyChange
update
jfreerails.client.renderer.AbstractTileRenderer
Javadoc:
/** * This class encapsulates the visible properties of a tile. * * @author Luke Lindsay */
Source code:
/**
* This class encapsulates the visible properties of a tile.
*
* @author Luke Lindsay
*/
public abstract class AbstractTileRenderer implements TileRenderer {
private final int[] typeNumbers;
private Image[] tileIcons;
private final TerrainType tileModel;
AbstractTileRenderer(TerrainType t, int[] rgbValues) {
tileModel = t;
this.typeNumbers = rgbValues;
if (null == t) {
throw new NullPointerException();
}
if (null == rgbValues) {
throw new NullPointerException();
}
}
public void renderTile(java.awt.Graphics g, int screenX, int screenY,
int mapX, int mapY, ReadOnlyWorld w) {
Image icon = this.getIcon(mapX, mapY, w);
if (null != icon) {
g.drawImage(icon, screenX, screenY, null);
}
}
public Image getDefaultIcon() {
return getTileIcons()[0];
}
String getTerrainType() {
return tileModel.getTerrainTypeName();
}
/**
* Returns an icon for the tile at x,y, which may depend on the terrain
* types of of the surrounding tiles.
*/
Image getIcon(int x, int y, ReadOnlyWorld w) {
int tile = selectTileIcon(x, y, w);
if (getTileIcons()[tile] != null) {
return getTileIcons()[tile];
}
throw new NullPointerException("Error in TileView.getIcon: icon no. "
+ tile + "==null");
}
int selectTileIcon(int x, int y, ReadOnlyWorld w) {
return 0;
}
int checkTile(int x, int y, ReadOnlyWorld w) {
int match = 0;
if (((x < w.getMapWidth()) && (x >= 0)) && (y < w.getMapHeight())
&& (y >= 0)) {
for (int i = 0; i < typeNumbers.length; i++) {
TerrainTile tt = (TerrainTile) w.getTile(x, y);
if (tt.getTerrainTypeID() == typeNumbers[i]) {
match = 1;
// A match
}
}
} else {
match = 1; // A match
/*
* If the tile we are checking is off the map, let it be a match.
* This stops coast appearing where the ocean meets the map edge.
*/
}
return match;
}
abstract public void dumpImages(ImageManager imageManager);
String generateRelativeFileName(int i) {
return "terrain" + File.separator + this.getTerrainType() + "_"
+ generateFileNameNumber(i) + ".png";
}
protected abstract String generateFileNameNumber(int i);
void setTileIcons(Image[] tileIcons) {
this.tileIcons = tileIcons;
}
Image[] getTileIcons() {
return tileIcons;
}
}
Methods:
MethodJavadoc
checkTile
dumpImages
generateFileNameNumber
generateRelativeFileName
getDefaultIcon
getIcon/**
getTerrainType
getTileIcons
renderTile
selectTileIcon
setTileIcons
jfreerails.client.renderer.BlankMapRenderer
Javadoc:
/** * Used for testing the Map view components without setting up any map data. * * @author Luke */
Source code:
/**
* Used for testing the Map view components without setting up any map data.
*
* @author Luke
*/
public class BlankMapRenderer implements MapRenderer {
private final float scale;
public BlankMapRenderer(float s) {
scale = s;
}
public float getScale() {
return scale;
}
public Dimension getMapSizeInPixels() {
int height = (int) (400 * scale);
int width = (int) (400 * scale);
return new Dimension(height, width);
}
public void paintTile(Graphics g, int tileX, int tileY) {
paintRect(g, null);
}
public void refreshTile(int x, int y) {
}
public void paintRect(Graphics g, Rectangle visibleRect) {
g.setColor(Color.darkGray);
g.fillRect(0, 0, (int) (scale * 400), (int) (scale * 400));
g.setColor(Color.blue);
int x = (int) (100 * scale);
int y = (int) (100 * scale);
int height = (int) (200 * scale);
int width = (int) (200 * scale);
g.fillRect(x, y, height, width);
}
public void refreshAll() {
// do nothing
}
}
Methods:
MethodJavadoc
getMapSizeInPixels
getScale
paintRect
paintTile/**
refreshAll
refreshTile
jfreerails.client.renderer.BufferedTiledBackgroundRenderer
Javadoc:
/** * This abstract class stores a buffer of the background of the current visible * rectangle of the map. Code that is independent of how tiles are represented, * e.g. whether they are square or isometric, should go here. * * @author Luke Lindsay 06 October 2001 * @version 1.0 * */
Source code:
/**
* This abstract class stores a buffer of the background of the current visible
* rectangle of the map. Code that is independent of how tiles are represented,
* e.g. whether they are square or isometric, should go here.
*
* @author Luke Lindsay 06 October 2001
* @version 1.0
*
*/
public abstract class BufferedTiledBackgroundRenderer implements
MapLayerRenderer {
/**
* This is used to create images that are compatible with the default
* graphics configuration. Such images can be drawn to the screen quickly
* since no conversion is needed.
*/
private final GraphicsConfiguration defaultConfig = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
/**
* Used to draw on the backbuffer.
*/
Graphics bg;
/**
* Used to draw on the backbuffer. It is translated so that to its users, it
* appears they are drawing on the actual map, not a buffered region of the
* map.
*
* translatedBg equals bg.translate(-bufferRect.x , -bufferRect.y);
*/
private Graphics translatedBg;
/**
* The bounds and location of the map region that is stored in the offscreen
* Image backgroundBuffer.
*/
final Rectangle bufferRect = new Rectangle();
/**
* An offscreen image storing the background of a region of the map.
*/
VolatileImage backgroundBuffer;
/**
* Updates the backbuffer as necessary, then draws it on to the Graphics
* object passed.
*
* @param outputGraphics
* Once it has been updated, the backbuffer is drawn onto this
* Graphics object.
* @param newVisibleRectangle
* The region of the map that the backbuffer must be updated to
* display.
*/
public void paintRect(Graphics outputGraphics,
Rectangle newVisibleRectangle) {
do {
/*
* If this is the first call to the paint method or the component
* has just been resized, we need to create a new backgroundBuffer.
*/
if ((backgroundBuffer == null)
|| (newVisibleRectangle.height != bufferRect.height)
|| (newVisibleRectangle.width != bufferRect.width)) {
setbackgroundBuffer(newVisibleRectangle.width,
newVisibleRectangle.height);
}
// Test if image is lost and restore it.
int valCode = backgroundBuffer.validate(defaultConfig);
if (valCode == VolatileImage.IMAGE_INCOMPATIBLE) {
setbackgroundBuffer(newVisibleRectangle.width,
newVisibleRectangle.height);
} else if (valCode == VolatileImage.IMAGE_RESTORED) {
resetGraphics();
this.refreshBackground();
}
/*
* Has the VisibleRectangle moved since the last paint?
*/
if ((bufferRect.x != newVisibleRectangle.x)
|| (bufferRect.y != newVisibleRectangle.y)) {
int dx = bufferRect.x - newVisibleRectangle.x;
int dy = bufferRect.y - newVisibleRectangle.y;
scrollbackgroundBuffer(dx, dy);
bufferRect.setBounds(newVisibleRectangle);
}
if ((bufferRect.width != newVisibleRectangle.width)
&& (bufferRect.height != newVisibleRectangle.height)) {
paintBufferRectangle(newVisibleRectangle.x - bufferRect.x,
newVisibleRectangle.y - bufferRect.y,
newVisibleRectangle.width,
newVisibleRectangle.height);
}
outputGraphics.drawImage(backgroundBuffer,
newVisibleRectangle.x, newVisibleRectangle.y, null);
bufferRect.setBounds(newVisibleRectangle);
} while (backgroundBuffer.contentsLost());
}
private void refreshBackground() {
paintBufferRectangle(0, 0, bufferRect.width, bufferRect.height);
}
public void refreshAll() {
refreshBackground();
}
private void setbackgroundBuffer(int w, int h) {
// Releases VRAM used by backgroundBuffer.
if (backgroundBuffer != null) {
backgroundBuffer.flush();
}
// Create new backgroundBuffer.
backgroundBuffer = defaultConfig.createCompatibleVolatileImage(w, h);
bufferRect.height = backgroundBuffer.getHeight(null);
bufferRect.width = backgroundBuffer.getWidth(null);
resetGraphics();
bg.clearRect(0, 0, w, h);
refreshBackground();
}
/** When the VolatileImage is created or restored, we need to (re)create the
Graphics objects.
*/
private void resetGraphics() {
if (bg != null) {
bg.dispose();
}
bg = backgroundBuffer.getGraphics();
if (translatedBg != null) {
translatedBg.dispose();
}
translatedBg = bg.create();
translatedBg.translate(-bufferRect.x, -bufferRect.y);
}
protected abstract void paintBufferRectangle(int x, int y, int width,
int height);
private void scrollbackgroundBuffer(int dx, int dy) {
int copyWidth = bufferRect.width;
int copyHeight = bufferRect.height;
int copySourceX = 0;
int copySourceY = 0;
if (dx > 0) {
copyWidth -= dx;
} else {
copyWidth += dx;
copySourceX = -dx;
}
if (dy > 0) {
copyHeight -= dy;
} else {
copyHeight += dy;
copySourceY = -dy;
}
bg.copyArea(copySourceX, copySourceY, copyWidth, copyHeight, dx, dy);
bufferRect.x -= dx;
bufferRect.y -= dy;
// paint exposed areas
if (dx != 0) {
if (dx > 0) {
bg.setClip(0, 0, dx, bufferRect.height);
bg.clearRect(0, 0, dx, bufferRect.height);
paintBufferRectangle(0, 0, dx, bufferRect.height);
} else {
bg.setClip(bufferRect.width + dx, 0, -dx, bufferRect.height);
bg.clearRect(bufferRect.width + dx, 0, -dx, bufferRect.height);
paintBufferRectangle(bufferRect.width + dx, 0, -dx,
bufferRect.height);
}
}
if (dy != 0) {
if (dy > 0) {
bg.setClip(0, 0, bufferRect.width, dy);
bg.clearRect(0, 0, bufferRect.width, dy);
paintBufferRectangle(0, 0, bufferRect.width, dy);
} else {
bg.setClip(0, bufferRect.height + dy, bufferRect.width, -dy);
bg.clearRect(0, bufferRect.height + dy, bufferRect.width, -dy);
paintBufferRectangle(0, bufferRect.height + dy,
bufferRect.width, -dy);
}
}
bg.setClip(0, 0, bufferRect.width, bufferRect.height);
}
}
Methods:
MethodJavadoc
paintBufferRectangle
paintRect/**
refreshAll
refreshBackground
resetGraphics/** When the VolatileImage is created or restored, we need to (re)create the
scrollbackgroundBuffer
setbackgroundBuffer
jfreerails.client.renderer.BuildTrackController
Javadoc:
/** * This class provides methods to change the proposed track and save it to the * real world. * * TODO jfreerails.client.renderer is not the most logical place for this class. * * @author MystiqueAgent * @author Luke * */
Source code:
/**
* This class provides methods to change the proposed track and save it to the
* real world.
*
* TODO jfreerails.client.renderer is not the most logical place for this class.
*
* @author MystiqueAgent
* @author Luke
*
*/
public class BuildTrackController implements GameModel {
private static final Logger LOGGER = Logger
.getLogger(BuildTrackController.class.getName());
private boolean buildNewTrack = true;
private List<ImPoint> builtTrack = new ArrayList<ImPoint>();
private boolean isBuildTrackSuccessful = false;
private final ModelRoot modelRoot;
private Step[] path;
private TrackPathFinder path4newTrackFinder;
private PathOnTrackFinder pathOnExistingTrackFinder;
private FreerailsPrincipal principal;
private ReadOnlyWorld realWorld;
private SoundManager soundManager = SoundManager.getSoundManager();
private ImPoint startPoint;
private ImPoint targetPoint;
private boolean visible = false;
private WorldDiffs worldDiffs;
/**
* BuildTrackRenderer
*
* @param readOnlyWorld
* ReadOnlyWorld
*/
public BuildTrackController(ReadOnlyWorld readOnlyWorld, ModelRoot modelRoot) {
worldDiffs = new WorldDiffs(readOnlyWorld);
realWorld = readOnlyWorld;
path4newTrackFinder = new TrackPathFinder(readOnlyWorld, modelRoot
.getPrincipal());
pathOnExistingTrackFinder = new PathOnTrackFinder(readOnlyWorld);
this.modelRoot = modelRoot;
principal = modelRoot.getPrincipal();
setWorldDiffs(worldDiffs);
}
/** Utility method that gets the BuildTrackStrategy from the model root. */
private BuildTrackStrategy getBts() {
BuildTrackStrategy btss = (BuildTrackStrategy) modelRoot
.getProperty(ModelRoot.Property.BUILD_TRACK_STRATEGY);
if (null == btss)
throw new NullPointerException();
return btss;
}
/** Utility method that gets the cursor position from the model root. */
private ImPoint getCursorPosition() {
ImPoint point = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.CURSOR_POSITION);
// Check for null & make a defensive copy
point = null == point ? new ImPoint() : point;
if (!modelRoot.getWorld().boundsContain(point.x, point.y)) {
throw new IllegalStateException(String.valueOf(point));
}
return point;
}
/** Hides and cancels any proposed track. */
public void hide() {
this.setVisible(false);
setTargetPoint(null);
reset();
}
/**
* returns <code>true</code> if the track is being build - it is iff the
* build track is shown
*
* @return boolean
*/
public boolean isBuilding() {
return visible;
}
/** Returns true if all the track pieces can be successfully built. */
public boolean isBuildTrackSuccessful() {
return isBuildTrackSuccessful;
}
/** Moves cursor which causes track to be built on the worldDiff object. */
private void moveCursorMoreTiles(List<ImPoint> track) {
moveCursorMoreTiles(track, null);
}
/**
* uses <code>trackBuilder</code> if not null -- otherwise uses own
* <code>buildTrack</code> method - that is applied on
* <code>worldDifferences</code>
*
* @param track
* List
* @param trackBuilder
* TrackMoveProducer
*/
private MoveStatus moveCursorMoreTiles(List<ImPoint> track,
TrackMoveProducer trackBuilder) {
ImPoint oldPosition = getCursorPosition();
if(!Step.checkValidity(oldPosition, track.get(0))){
throw new IllegalStateException(oldPosition.toString()+ " and "+track.get(0).toString());
}
MoveStatus ms = null;
int piecesOfNewTrack = 0;
if (null != trackBuilder) {
trackBuilder.setBuildTrackStrategy(getBts());
}
for (Iterator<ImPoint> iter = track.iterator(); iter.hasNext();) {
ImPoint point = iter.next();
LOGGER.fine("point" + point);
LOGGER.fine("oldPosition" + oldPosition);
if (oldPosition.equals(point)) {
LOGGER.fine("(oldPosition.equals(point))" + point);
continue;
}
Step vector = Step.getInstance(point.x - oldPosition.x, point.y
- oldPosition.y);
// If there is already track between the two tiles, do nothing
FreerailsTile tile = (FreerailsTile) realWorld.getTile(
oldPosition.x, oldPosition.y);
if (tile.getTrackPiece().getTrackConfiguration().contains(vector)) {
oldPosition = point;
continue;
}
piecesOfNewTrack++;
if (trackBuilder != null) {
ms = trackBuilder.buildTrack(oldPosition, vector);
} else {
ms = planBuildingTrack(oldPosition, vector);
}
if (ms.ok) {
setCursorMessage("");
} else {
setCursorMessage(ms.message);
reset();
return ms;
}
oldPosition = point;
}
/* Check whether there is already track at every point. */
if (piecesOfNewTrack == 0) {
MoveStatus moveFailed = MoveStatus.moveFailed("Track already here");
setCursorMessage(moveFailed.message);
return moveFailed;
}
isBuildTrackSuccessful = true;
// If track has actually been built, play the build track sound.
if (trackBuilder != null && ms.isOk()) {
if (trackBuilder.getTrackBuilderMode() == BUILD_TRACK) {
this.soundManager.playSound(
"/jfreerails/client/sounds/buildtrack.wav", 0);
}
}
return ms;
}
/**
* Attempts to building track from the specified point in the specified
* direction on the worldDiff object.
*/
private MoveStatus planBuildingTrack(ImPoint point, Step vector) {
FreerailsTile tileA = (FreerailsTile) worldDiffs.getTile(point.x,
point.y);
BuildTrackStrategy bts = getBts();
int trackTypeAID = bts.getRule(tileA.getTerrainTypeID());
TrackRule trackRuleA = (TrackRule) worldDiffs.get(SKEY.TRACK_RULES,
trackTypeAID);
FreerailsTile tileB = (FreerailsTile) worldDiffs.getTile(point.x
+ vector.deltaX, point.y + vector.deltaY);
int trackTypeBID = bts.getRule(tileB.getTerrainTypeID());
TrackRule trackRuleB = (TrackRule) worldDiffs.get(SKEY.TRACK_RULES,
trackTypeBID);
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(point, vector, trackRuleA, trackRuleB,
worldDiffs, principal);
return move.doMove(worldDiffs, principal);
}
/** Cancels any proposed track and resets the path finder. */
private void reset() {
worldDiffs.reset();
path4newTrackFinder.abandonSearch();
this.builtTrack.clear();
this.isBuildTrackSuccessful = false;
}
int searchStatus() {
if (buildNewTrack) {
return path4newTrackFinder.getStatus();
}
return pathOnExistingTrackFinder.getStatus();
}
/** Utility method that sets the CURSOR_MESSAGE property on the model root. */
private void setCursorMessage(String s) {
modelRoot.setProperty(ModelRoot.Property.CURSOR_MESSAGE, s);
}
/** Sets the proposed track: from the current cursor position to the specified point.*/
public void setProposedTrack(ImPoint to,
TrackMoveProducer trackBuilder) {
ImPoint from = getCursorPosition();
assert (trackBuilder.getTrackBuilderMode() != IGNORE_TRACK);
assert (trackBuilder.getTrackBuilderMode() != BUILD_STATION);
buildNewTrack = trackBuilder.getTrackBuilderMode() == BUILD_TRACK;
/*
* If we have just found the route between the two points, don't waste
* time doing it again.
*/
if (null != targetPoint && null != startPoint
&& targetPoint.equals(to)
&& startPoint.equals(from)
&& searchStatus() != IncrementalPathFinder.SEARCH_NOT_STARTED) {
return;
}
worldDiffs.reset();
builtTrack.clear();
isBuildTrackSuccessful = false;
if (from.equals(to)) {
hide();
return;
}
/* Check both points are on the map. */
if (!realWorld.boundsContain(from.x, from.y)
|| !realWorld.boundsContain(to.x, to.y)) {
hide();
return;
}
setTargetPoint(to);
startPoint = from;
try {
BuildTrackStrategy bts = getBts();
if (buildNewTrack) {
path4newTrackFinder.setupSearch(from, to, bts);
} else {
pathOnExistingTrackFinder.setupSearch(from, to);
}
} catch (PathNotFoundException e) {
setCursorMessage(e.getMessage());
return;
}
updateSearch();
}
/**
* @param newTargetPoint
* The m_targetPoint to set.
*/
private void setTargetPoint(ImPoint newTargetPoint) {
this.targetPoint = newTargetPoint;
ImPoint p = null == newTargetPoint ? null : newTargetPoint;
modelRoot.setProperty(ModelRoot.Property.THINKING_POINT, p);
}
private void setVisible(boolean show) {
if (show == visible) {
return;
}
if (show) {
setWorldDiffs(worldDiffs);
} else {
setWorldDiffs(null);
}
this.visible = show;
}
private void setWorldDiffs(WorldDiffs worldDiffs) {
modelRoot.setProperty(ModelRoot.Property.PROPOSED_TRACK, worldDiffs);
}
public void show() {
this.setVisible(true);
}
public void update() {
// update search for path if necessary.
if (searchStatus() == IncrementalPathFinder.SEARCH_PAUSED) {
updateSearch();
}
}
public void updateUntilComplete() {
while (searchStatus() != IncrementalPathFinder.PATH_FOUND) {
updateSearch();
}
}
/**
* Updates the search, if the search is completed, the proposed track is
* shown.
*/
private void updateSearch() {
try {
if (buildNewTrack) {
path4newTrackFinder.search(100);
} else {
pathOnExistingTrackFinder.search(100);
}
} catch (PathNotFoundException e) {
setCursorMessage(e.getMessage());
return;
}
if (searchStatus() == IncrementalPathFinder.PATH_FOUND) {
if (buildNewTrack) {
builtTrack = path4newTrackFinder.pathAsPoints();
moveCursorMoreTiles(builtTrack);
} else {
boolean okSoFar = true;
path = pathOnExistingTrackFinder.pathAsVectors();
TrackMoveProducer.BuildMode mode = getBuildMode();
int locationX = startPoint.x;
int locationY = startPoint.y;
FreerailsPrincipal fp = modelRoot.getPrincipal();
for (Step v : path) {
Move move;
attemptMove: {
switch (mode) {
case REMOVE_TRACK:
try {
move = ChangeTrackPieceCompositeMove
.generateRemoveTrackMove(new ImPoint(
locationX, locationY), v,
worldDiffs, fp);
break;
} catch (Exception e1) {
e1.printStackTrace();
break attemptMove;
}
case UPGRADE_TRACK:
int owner = ChangeTrackPieceCompositeMove.getOwner(
fp, worldDiffs);
FreerailsTile tile = (FreerailsTile) worldDiffs
.getTile(locationX, locationY);
int tt = tile.getTerrainTypeID();
int trackRuleID = getBts().getRule(tt);
/*
* Skip tiles that already have the right track
* type.
*/
if (trackRuleID == tile.getTrackPiece().getTrackTypeID()) {
break attemptMove;
}
TrackRule trackRule = (TrackRule) worldDiffs.get(
SKEY.TRACK_RULES, trackRuleID);
TrackPiece after = new TrackPieceImpl(tile
.getTrackPiece().getTrackConfiguration(), trackRule, owner,
trackRuleID);
/*
* We don't want to 'upgrade' a station to track.
* See bug 874416.
*/
if (tile.getTrackPiece().getTrackRule().isStation()) {
break attemptMove;
}
move = UpgradeTrackMove.generateMove(tile
.getTrackPiece(), after, new ImPoint(
locationX, locationY));
break;
default:
throw new IllegalStateException(mode.toString());
}// end of switch statement
MoveStatus ms = move.doMove(worldDiffs, fp);
okSoFar = ms.ok && okSoFar;
}// end of attemptMove
locationX += v.deltaX;
locationY += v.deltaY;
}// end for loop
startPoint = new ImPoint(locationX, locationY);
isBuildTrackSuccessful = okSoFar;
if (okSoFar) {
setCursorMessage("");
}
}
show();
}
}
private TrackMoveProducer.BuildMode getBuildMode() {
TrackMoveProducer.BuildMode mode;
mode = (TrackMoveProducer.BuildMode) modelRoot
.getProperty(ModelRoot.Property.TRACK_BUILDER_MODE);
return mode;
}
/**
* Saves track into real world
*/
public ImPoint updateWorld(TrackMoveProducer trackBuilder) {
ImPoint actPoint = getCursorPosition();
if (buildNewTrack) {
if (builtTrack.size() > 0) {
MoveStatus ms = moveCursorMoreTiles(builtTrack, trackBuilder);
/* Note, reset() will have been called if ms.ok == false */
if (ms.ok) {
actPoint = builtTrack.get(builtTrack.size() - 1);
builtTrack = new ArrayList<ImPoint>();
}
}
} else {
trackBuilder.setBuildTrackStrategy(getBts());
MoveStatus ms = trackBuilder.buildTrack(actPoint, path);
//MoveStatus ms = trackBuilder.buildTrack(startPoint, path);
if (ms.ok) {
actPoint = targetPoint;
setCursorMessage("");
if (REMOVE_TRACK == getBuildMode()) {
soundManager.playSound(
"/jfreerails/client/sounds/removetrack.wav", 0);
} else {
soundManager.playSound(
"/jfreerails/client/sounds/buildtrack.wav", 0);
}
} else {
setCursorMessage(ms.message);
reset();
}
}
hide();
return actPoint;
}
}
Methods:
MethodJavadoc
getBts/** Utility method that gets the BuildTrackStrategy from the model root. */
getBuildMode
getCursorPosition/** Utility method that gets the cursor position from the model root. */
hide/** Hides and cancels any proposed track. */
isBuildTrackSuccessful/** Returns true if all the track pieces can be successfully built. */
isBuilding/**
moveCursorMoreTiles/** Moves cursor which causes track to be built on the worldDiff object. */
moveCursorMoreTiles/**
planBuildingTrack/**
reset/** Cancels any proposed track and resets the path finder. */
searchStatus
setCursorMessage/** Utility method that sets the CURSOR_MESSAGE property on the model root. */
setProposedTrack/** Sets the proposed track: from the current cursor position to the specified point.*/
setTargetPoint/**
setVisible
setWorldDiffs
show
update
updateSearch/**
updateUntilComplete
updateWorld/**
jfreerails.client.renderer.BuildTrackRenderer
Javadoc:
/** * This class draws the track being build. * * @author MystiqueAgent * @author Luke * */
Source code:
/**
* This class draws the track being build.
*
* @author MystiqueAgent
* @author Luke
*
*/
public class BuildTrackRenderer implements Painter {
public static final int BIG_DOT_WIDTH = 12;
public static final int SMALL_DOT_WIDTH = 6;
private final ModelRoot modelRoot;
private final Dimension tileSize = new Dimension(30, 30);
private RenderersRoot rr;
public BuildTrackRenderer(RenderersRoot trackPieceViewList,
ModelRoot modelRoot) {
this.modelRoot = modelRoot;
this.rr = trackPieceViewList;
}
private WorldDiffs getWorldDiffs() {
if (modelRoot == null) {
return null;
}
return (WorldDiffs) modelRoot
.getProperty(ModelRoot.Property.PROPOSED_TRACK);
}
/**
* Paints the proposed track and dots to distinguish the proposed track from
* any existing track.
*/
public void paint(Graphics2D g) {
WorldDiffs worldDiffs = getWorldDiffs();
if (null != worldDiffs) {
for (Iterator<ImPoint> iter = worldDiffs.getMapDiffs(); iter
.hasNext();) {
ImPoint point = iter.next();
FreerailsTile fp = (FreerailsTile)worldDiffs.getTile(point.x,
point.y);
TrackPiece tp = fp.getTrackPiece();
int graphicsNumber = tp.getTrackGraphicID();
int ruleNumber = tp.getTrackTypeID();
jfreerails.client.renderer.TrackPieceRenderer trackPieceView = rr
.getTrackPieceView(ruleNumber);
trackPieceView.drawTrackPieceIcon(graphicsNumber, g, point.x,
point.y, tileSize);
}
ReadOnlyWorld realWorld = modelRoot.getWorld();
/*
* Draw small dots for each tile whose track has changed. The dots
* are white if track has been added or upgraded and red if it has
* been removed.
*/
for (Iterator<ImPoint> iter = worldDiffs.getMapDiffs(); iter
.hasNext();) {
ImPoint p = iter.next();
int x = p.x * tileSize.width
+ (tileSize.width - SMALL_DOT_WIDTH) / 2;
int y = p.y * tileSize.width
+ (tileSize.height - SMALL_DOT_WIDTH) / 2;
FreerailsTile before = (FreerailsTile) realWorld.getTile(p.x,
p.y);
FreerailsTile after = (FreerailsTile) worldDiffs.getTile(p.x,
p.y);
boolean trackRemoved = !after.getTrackPiece().getTrackConfiguration().contains(
before.getTrackPiece().getTrackConfiguration());
Color dotColor = trackRemoved ? Color.RED : Color.WHITE;
g.setColor(dotColor);
g.fillOval(x, y, SMALL_DOT_WIDTH, SMALL_DOT_WIDTH);
}
}
}
}
Methods:
MethodJavadoc
getWorldDiffs
paint/**
jfreerails.client.renderer.ChequeredTileRenderer
Javadoc:
/** * Paints 2 variations of a tile icon a chequered pattern. * * @author Luke Lindsay */
Source code:
/**
* Paints 2 variations of a tile icon a chequered pattern.
*
* @author Luke Lindsay
*/
final public class ChequeredTileRenderer extends AbstractTileRenderer {
@Override
public int selectTileIcon(int x, int y, ReadOnlyWorld w) {
return (x + y) % 2;
}
public ChequeredTileRenderer(ImageManager imageManager, int[] rgbValues,
TerrainType tileModel) throws IOException {
super(tileModel, rgbValues);
this.setTileIcons(new Image[2]);
this.getTileIcons()[0] = imageManager
.getImage(generateRelativeFileName(0));
this.getTileIcons()[1] = imageManager
.getImage(generateRelativeFileName(1));
}
@Override
public void dumpImages(ImageManager imageManager) {
for (int i = 0; i < this.getTileIcons().length; i++) {
String fileName = generateRelativeFileName(i);
imageManager.setImage(fileName, this.getTileIcons()[i]);
}
}
@Override
protected String generateFileNameNumber(int i) {
return String.valueOf(i);
}
}
Methods:
MethodJavadoc
dumpImages
generateFileNameNumber
selectTileIcon
jfreerails.client.renderer.CityNamesRenderer
Javadoc:
/** * Paints the city names on the map. * * @author Scott */
Source code:
/**
* Paints the city names on the map.
*
* @author Scott
*/
public class CityNamesRenderer implements Painter {
private final ReadOnlyWorld w;
public CityNamesRenderer(ReadOnlyWorld world) {
this.w = world;
}
public void paint(Graphics2D g) {
g.setColor(Color.WHITE);
g.setFont(new Font("Arial", 0, 20));
// draw city names onto map
for (int i = 0; i < w.size(SKEY.CITIES); i++) {
CityModel tempCity = (CityModel) w.get(SKEY.CITIES, i);
g.drawString(tempCity.getCityName(), tempCity.getCityX() * 30,
tempCity.getCityY() * 30 + 10);
}
}
}
Methods:
MethodJavadoc
paint
jfreerails.client.renderer.ForestStyleTileRenderer
Javadoc:
/** * Looks to see whether the tiles to the left and right of the same type when * deciding which tile icon to use. * * @author Luke Lindsay */
Source code:
/**
* Looks to see whether the tiles to the left and right of the same type when
* deciding which tile icon to use.
*
* @author Luke Lindsay
*/
final public class ForestStyleTileRenderer extends
jfreerails.client.renderer.AbstractTileRenderer {
private static final int[] X_LOOK_AT = { -1, 1 };
private static final int[] Y_LOOK_AT = { 0, 0 };
public ForestStyleTileRenderer(ImageManager imageManager, int[] rgbValues,
TerrainType tileModel) throws IOException {
super(tileModel, rgbValues);
this.setTileIcons(new Image[4]);
for (int i = 0; i < this.getTileIcons().length; i++) {
String fileName = generateRelativeFileName(i);
this.getTileIcons()[i] = imageManager.getImage(fileName);
}
}
@Override
public int selectTileIcon(int x, int y, ReadOnlyWorld w) {
int iconNumber = 0;
for (int i = 0; i < 2; i++) {
iconNumber = iconNumber
| checkTile(x + X_LOOK_AT[i], y + Y_LOOK_AT[i], w);
iconNumber = iconNumber << 1;
}
iconNumber = iconNumber >> 1;
return iconNumber;
}
@Override
public void dumpImages(ImageManager imageManager) {
for (int i = 0; i < this.getTileIcons().length; i++) {
String fileName = generateRelativeFileName(i);
imageManager.setImage(fileName, this.getTileIcons()[i]);
}
}
@Override
protected String generateFileNameNumber(int i) {
return BinaryNumberFormatter.format(i, 2);
}
}
Methods:
MethodJavadoc
dumpImages
generateFileNameNumber
selectTileIcon
jfreerails.client.renderer.MapBackgroundRender
Javadoc:
/** * This class encapsulates the objects that make-up and paint the background of * the map view. At present it is composed of two layers: the terrain layer and * the track layer. * * @author Luke Lindsay 21 September 2001 * @version 1 */
Source code:
/**
* This class encapsulates the objects that make-up and paint the background of
* the map view. At present it is composed of two layers: the terrain layer and
* the track layer.
*
* @author Luke Lindsay 21 September 2001
* @version 1
*/
final public class MapBackgroundRender implements MapLayerRenderer {
private static final Logger logger = Logger
.getLogger(MapBackgroundRender.class.getName());
/**
* The terrain layer.
*/
private final TerrainLayer terrainLayer;
/**
* The track layer.
*/
private final TrackLayer trackLayer;
private final Dimension tileSize = new Dimension(30, 30);
private final Dimension mapSize;
private final Painter cityNames;
private final Painter stationNames;
/*
* Used to avoid having to create a new rectangle for each call to the paint
* methods.
*/
private Rectangle clipRectangle = new Rectangle();
/**
* This inner class represents a view of the track on the map.
*
* @author Luke Lindsay 21 September 2001
*/
final public class TrackLayer implements MapLayerRenderer {
private final ReadOnlyWorld w;
private final RenderersRoot rr;
/**
* Paints a rectangle of tiles onto the supplied graphics context.
*
* @param g
* The graphics context on which the tiles get painted.
* @param tilesToPaint
* The rectangle, measured in tiles, to paint.
*/
public void paintRectangleOfTiles(Graphics g, Rectangle tilesToPaint) {
/*
* Track can overlap the adjacent terrain tiles by half a tile. This
* means that we need to paint the track from the tiles bordering
* the specified rectangle of tiles (tilesToPaint). To prevent
* unnecessary painting, we set the clip to expose only the rectangle
* of tilesToPaint.
*/
Graphics tempG = g;
Point tile = new Point();
for (tile.x = tilesToPaint.x - 1; tile.x < (tilesToPaint.x
+ tilesToPaint.width + 1); tile.x++) {
for (tile.y = tilesToPaint.y - 1; tile.y < (tilesToPaint.y
+ tilesToPaint.height + 1); tile.y++) {
if ((tile.x >= 0) && (tile.x < mapSize.width)
&& (tile.y >= 0) && (tile.y < mapSize.height)) {
FreerailsTile ft = (FreerailsTile)w.getTile(tile.x, tile.y);
TrackPiece tp = ft.getTrackPiece();
int graphicsNumber = tp.getTrackGraphicID();
int ruleNumber = tp.getTrackTypeID();
if (ruleNumber != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
TrackPieceRenderer trackPieceView = rr.getTrackPieceView(ruleNumber);
trackPieceView.drawTrackPieceIcon(graphicsNumber,
tempG, tile.x, tile.y, tileSize);
}
}
}
}
}
public void paintTile(Graphics g, int tileX, int tileY) {
/*
* Since track tiles overlap the adjacent terrain tiles, we create a
* temporary Graphics object that only lets us draw on the selected
* tile.
*/
paintRectangleOfTiles(g, new Rectangle(tileX, tileY, 1, 1));
}
private void paintRectangleOfTiles(Graphics g, int x, int y, int width,
int height) {
paintRectangleOfTiles(g, new Rectangle(x, y, width, height));
}
public void refreshTile(int x, int y) {
}
public void paintRect(Graphics g, Rectangle visibleRect) {
throw new UnsupportedOperationException(
"Method not yet implemented.");
}
public TrackLayer(ReadOnlyWorld world,
RenderersRoot trackPieceViewList) {
this.rr = trackPieceViewList;
this.w = world;
}
public void refreshAll() {
}
}
/**
* This inner class represents the terrain of the map.
*
* @author Luke Lindsay 21 September 2001
*/
final public class TerrainLayer implements MapLayerRenderer {
private final TileRendererList tiles;
private final ReadOnlyWorld w;
public void paintTile(Graphics g, Point tile) {
int screenX = tileSize.width * tile.x;
int screenY = tileSize.height * tile.y;
if ((tile.x >= 0) && (tile.x < mapSize.width) && (tile.y >= 0)
&& (tile.y < mapSize.height)) {
TerrainTile tt = (TerrainTile) w.getTile(tile.x, tile.y);
int typeNumber = tt.getTerrainTypeID();
TileRenderer tr = tiles.getTileViewWithNumber(typeNumber);
if (null == tr) {
logger.warning("No tile renderer for " + typeNumber);
} else {
tr.renderTile(g, screenX, screenY, tile.x, tile.y, w);
}
}
}
/**
* Paints a rectangle of tiles on the supplied graphics context.
*
* @param g
* The graphics context.
* @param tilesToPaint
* The rectangle, measured in tiles, to paint.
*/
public void paintRectangleOfTiles(Graphics g, Rectangle tilesToPaint) {
Point tile = new Point();
for (tile.x = tilesToPaint.x; tile.x < (tilesToPaint.x + tilesToPaint.width); tile.x++) {
for (tile.y = tilesToPaint.y; tile.y < (tilesToPaint.y + tilesToPaint.height); tile.y++) {
terrainLayer.paintTile(g, tile);
}
}
}
public void paintRect(Graphics g, Rectangle visibleRect) {
throw new UnsupportedOperationException(
"Method not yet implemented.");
}
public void paintTile(Graphics g, int tileX, int tileY) {
paintTile(g, new Point(tileX, tileY));
}
private void paintRectangleOfTiles(Graphics g, int x, int y, int width,
int height) {
paintRectangleOfTiles(g, new Rectangle(x, y, width, height));
}
public void refreshTile(int x, int y) {
}
public TerrainLayer(ReadOnlyWorld world, TileRendererList tiles) {
this.w = world;
this.tiles = tiles;
}
public void refreshAll() {
}
}
public MapBackgroundRender(ReadOnlyWorld w, RenderersRoot rr,
ModelRoot modelRoot) {
trackLayer = new TrackLayer(w, rr);
terrainLayer = new TerrainLayer(w, rr);
mapSize = new Dimension(w.getMapWidth(), w.getMapHeight());
cityNames = new CityNamesRenderer(w);
stationNames = new StationNamesRenderer(w, modelRoot);
}
public void paintTile(Graphics g, int x, int y) {
terrainLayer.paintTile(g, x, y);
trackLayer.paintTile(g, x, y);
cityNames.paint((Graphics2D) g);
stationNames.paint((Graphics2D) g);
}
public void paintRect(Graphics g, Rectangle visibleRect) {
int tileWidth = 30;
int tileHeight = 30;
clipRectangle = g.getClipBounds(clipRectangle);
int x = clipRectangle.x / tileWidth;
int y = clipRectangle.y / tileHeight;
int width = (clipRectangle.width / tileWidth) + 2;
int height = (clipRectangle.height) / tileHeight + 2;
paintRectangleOfTiles(g, x, y, width, height);
cityNames.paint((Graphics2D) g);
stationNames.paint((Graphics2D) g);
}
private void paintRectangleOfTiles(Graphics g, int x, int y, int width,
int height) {
terrainLayer.paintRectangleOfTiles(g, x, y, width, height);
trackLayer.paintRectangleOfTiles(g, x, y, width, height);
cityNames.paint((Graphics2D) g);
stationNames.paint((Graphics2D) g);
}
public void refreshTile(int x, int y) {
// Do nothing
}
public void refreshAll() {
// Do nothing
}
}
Methods:
MethodJavadoc
paintRect
paintRectangleOfTiles
paintTile
refreshAll
refreshTile
jfreerails.client.renderer.MapLayerRenderer
Javadoc:
/** * Paints a layer of the map which might be buffered. * * @author Luke Lindsay */
Source code:
/**
* Paints a layer of the map which might be buffered.
*
* @author Luke Lindsay
*/
public interface MapLayerRenderer {
void paintTile(Graphics g, int tileX, int tileY);
void refreshTile(int x, int y);
void refreshAll();
void paintRect(Graphics g, Rectangle visibleRect);
}
Methods:
MethodJavadoc
paintRect
paintTile
refreshAll
refreshTile
jfreerails.client.renderer.MapRenderer
Javadoc:
/** * Lets the GUI component that is displaying the map known the scale at which * the map is being rendered. * * @author Luke */
Source code:
/**
* Lets the GUI component that is displaying the map known the scale at which
* the map is being rendered.
*
* @author Luke
*/
public interface MapRenderer extends MapLayerRenderer {
float getScale();
Dimension getMapSizeInPixels();
}
Methods:
MethodJavadoc
getMapSizeInPixels
getScale
jfreerails.client.renderer.MyRenderersRoot
Javadoc:
/** * The MyRenderersRoot class serves as the root renderer implementation for managing graphical resources * in a rail simulation application. It provides access to train images and handles image loading through * the ImageManager. This class implements the RenderersRoot interface and offers basic support for * retrieving train-related images, though several renderer methods remain unimplemented as stubs. * * @author [Author Name] * @see RenderersRoot * @see ImageManager * @see TrainImages */
Source code:
class MyRenderersRoot implements RenderersRoot {
static ImageManager imageManager = new ImageManagerImpl("/jfreerails/client/graphics/");
private TrainImages trainImages;
public MyRenderersRoot() {
try {
this.trainImages = new TrainImages(imageManager, "mail");
} catch (IOException ex) {
Logger.getLogger(MyRenderersRoot.class.getName()).log(Level.SEVERE, null, ex);
fail();
}
}
@Override
public TrackPieceRenderer getTrackPieceView(int i) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public TrainImages getWagonImages(int type) {
return this.trainImages;
}
@Override
public TrainImages getEngineImages(int type) {
return this.trainImages;
}
@Override
public boolean validate(ReadOnlyWorld world) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Image getImage(String relativeFilename) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Image getScaledImage(String relativeFilename, int height) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public TileRenderer getTileViewWithNumber(int i) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
Methods:
MethodJavadoc
getEngineImages
getImage
getScaledImage
getTileViewWithNumber
getTrackPieceView
getWagonImages
validate
jfreerails.client.renderer.NullTrackPieceRenderer
Javadoc:
/** * This class implements the TrackPieceView interface, but intentionally does * nothing. Its methods are called when drawing tiles with no track. * * @author Luke */
Source code:
/**
* This class implements the TrackPieceView interface, but intentionally does
* nothing. Its methods are called when drawing tiles with no track.
*
* @author Luke
*/
final public class NullTrackPieceRenderer implements TrackPieceRenderer {
public static final NullTrackPieceRenderer instance = new NullTrackPieceRenderer();
private NullTrackPieceRenderer() {
}
/*
* @see TrackPieceView#getTrackPieceIcon(int)
*/
public Image getTrackPieceIcon(int trackTemplate) {
return null;
}
/*
* @see TrackPieceView#drawTrackPieceIcon(int, Graphics, int, int,
* Dimension)
*/
public void drawTrackPieceIcon(int trackTemplate, Graphics g, int x, int y,
Dimension tileSize) {
// Draw nothing since there no track here.
}
public void dumpImages(ImageManager imageManager) {
// TODO Auto-generated method stub
}
}
Methods:
MethodJavadoc
drawTrackPieceIcon
dumpImages
getTrackPieceIcon
jfreerails.client.renderer.RenderersRoot
Javadoc:
/** * Provides access to the objects that render terrain, track, and trains. * * @author Luke */
Source code:
/**
* Provides access to the objects that render terrain, track, and trains.
*
* @author Luke
*/
public interface RenderersRoot extends TileRendererList {
TrackPieceRenderer getTrackPieceView(int i);
TrainImages getWagonImages(int type);
TrainImages getEngineImages(int type);
//OldTrainImages getTrainImages();
boolean validate(ReadOnlyWorld world);
Image getImage(String relativeFilename) throws IOException;
Image getScaledImage(String relativeFilename, int height) throws IOException;
}
Methods:
MethodJavadoc
getEngineImages
getImage
getScaledImage
getTrackPieceView
getWagonImages
validate
jfreerails.client.renderer.RiverStyleTileRenderer
Javadoc:
/** * Selects a tile icon to use based on the type of the tiles to the North, East, * South and West. * * @author Luke Lindsay */
Source code:
/**
* Selects a tile icon to use based on the type of the tiles to the North, East,
* South and West.
*
* @author Luke Lindsay
*/
final public class RiverStyleTileRenderer extends
jfreerails.client.renderer.AbstractTileRenderer {
private static final int[] Y_LOOK_AT = { 0, 1, 0, -1 };
private static final int[] X_LOOK_AT = { -1, 0, 1, 0 };
public RiverStyleTileRenderer(ImageManager imageManager, int[] rgbValues,
TerrainType tileModel) throws IOException {
super(tileModel, rgbValues);
this.setTileIcons(new Image[16]);
for (int i = 0; i < this.getTileIcons().length; i++) {
String fileName = generateRelativeFileName(i);
this.getTileIcons()[i] = imageManager.getImage(fileName);
}
}
@Override
public int selectTileIcon(int x, int y, ReadOnlyWorld w) {
int iconNumber = 0;
for (int i = 0; i < 4; i++) {
iconNumber = iconNumber << 1;
iconNumber = iconNumber
| checkTile(x + X_LOOK_AT[i], y + Y_LOOK_AT[i], w);
}
return iconNumber;
}
@Override
public void dumpImages(ImageManager imageManager) {
for (int i = 0; i < this.getTileIcons().length; i++) {
imageManager.setImage(generateRelativeFileName(i), this
.getTileIcons()[i]);
}
}
@Override
protected String generateFileNameNumber(int i) {
return BinaryNumberFormatter.formatWithLowBitOnLeft(i, 4);
}
}
Methods:
MethodJavadoc
dumpImages
generateFileNameNumber
selectTileIcon
jfreerails.client.renderer.SpecialTileRenderer
Javadoc:
/** * A special tile's icon gets drawn over the icon of a normal tile. * * @author Luke Lindsay */
Source code:
/**
* A special tile's icon gets drawn over the icon of a normal tile.
*
* @author Luke Lindsay
*/
final public class SpecialTileRenderer extends AbstractTileRenderer {
private static final Logger logger = Logger
.getLogger(SpecialTileRenderer.class.getName());
final private TileRenderer parentTileView;
@Override
public void renderTile(java.awt.Graphics g, int renderX, int renderY,
int mapX, int mapY, ReadOnlyWorld w) {
if (parentTileView != null) {
parentTileView.renderTile(g, renderX, renderY, mapX, mapY, w);
} else {
logger.warning("parent tileView==null");
}
Image icon = this.getIcon(mapX, mapX, w);
if (null != icon) {
g.drawImage(icon, renderX, renderY, null);
} else {
logger.warning("special tileView icon==null");
}
}
@Override
public int selectTileIcon(int x, int y, ReadOnlyWorld w) {
return 0;
}
public SpecialTileRenderer(ImageManager imageManager, int[] rgbValues,
TerrainType tileModel, TileRenderer parentTileView)
throws IOException {
super(tileModel, rgbValues);
this.setTileIcons(new Image[1]);
this.getTileIcons()[0] = imageManager.getImage(generateFilename());
this.parentTileView = parentTileView;
}
@Override
public void dumpImages(ImageManager imageManager) {
imageManager.setImage(generateFilename(), this.getTileIcons()[0]);
}
private String generateFilename() {
return "terrain" + File.separator + this.getTerrainType() + ".png";
}
@Override
protected String generateFileNameNumber(int i) {
throw new UnsupportedOperationException();
}
}
Methods:
MethodJavadoc
dumpImages/**
generateFileNameNumber
generateFilename
renderTile
selectTileIcon
jfreerails.client.renderer.SquareTileBackgroundRenderer
Javadoc:
/** * This class stores a buffer containing the terrain and track layers of current * visible rectangle of the map. It is responsible of painting these layers and * updating the buffer when the map scrolls or tiles are updated. * * @author Luke Lindsay 01 November 2001 * @version 1.0 */
Source code:
/**
* This class stores a buffer containing the terrain and track layers of current
* visible rectangle of the map. It is responsible of painting these layers and
* updating the buffer when the map scrolls or tiles are updated.
*
* @author Luke Lindsay 01 November 2001
* @version 1.0
*/
final public class SquareTileBackgroundRenderer extends BufferedTiledBackgroundRenderer {
private final MapLayerRenderer mapView;
@Override
protected void paintBufferRectangle(int x, int y, int width, int height) {
// Fix for bug [ 1303162 ]
// If the buffer hasn't been set yet, don't try and refresh it!
if (null != super.backgroundBuffer) {
Graphics gg = bg.create();
gg.setClip(x, y, width, height);
gg.translate(-bufferRect.x, -bufferRect.y);
mapView.paintRect(gg, bufferRect);
}
}
public SquareTileBackgroundRenderer(MapLayerRenderer mv) {
if (null == mv) {
throw new NullPointerException();
}
this.mapView = mv;
}
public void paintTile(Graphics g, int tileX, int tileY) {
mapView.paintTile(g, tileX, tileY);
}
public void refreshTile(int x, int y) {
// The backgroundBuffer gets created on the first call to
// backgroundBuffer.paintRect(..)
// so we need a check here to avoid a null pointer exception.
if (null != super.backgroundBuffer) {
Graphics gg = bg.create();
gg.translate(-bufferRect.x, -bufferRect.y);
mapView.paintTile(gg, x, y);
}
}
}
Methods:
MethodJavadoc
paintBufferRectangle
paintTile
refreshTile
jfreerails.client.renderer.StandardTileRenderer
Javadoc:
/** * Paints a tile for which there only one tile icon. * * @author Luke Lindsay */
Source code:
/**
* Paints a tile for which there only one tile icon.
*
* @author Luke Lindsay
*/
final public class StandardTileRenderer extends
jfreerails.client.renderer.AbstractTileRenderer {
public StandardTileRenderer(ImageManager imageManager, int[] rgbValues,
TerrainType tileModel) throws IOException {
super(tileModel, rgbValues);
this.setTileIcons(new Image[1]);
this.getTileIcons()[0] = imageManager.getImage(generateFilename());
}
@Override
public void dumpImages(ImageManager imageManager) {
imageManager.setImage(generateFilename(), this.getTileIcons()[0]);
}
private String generateFilename() {
return generateFilename(this.getTerrainType());
}
public static String generateFilename(String typeName) {
return "terrain" + File.separator + typeName + ".png";
}
@Override
protected String generateFileNameNumber(int i) {
throw new UnsupportedOperationException();
}
}
Methods:
MethodJavadoc
dumpImages/**
generateFileNameNumber
generateFilename
generateFilename
jfreerails.client.renderer.StationBoxRenderer
Javadoc:
/** * Renders box showing the cargo waiting at a station. * * @author Luke */
Source code:
/**
* Renders box showing the cargo waiting at a station.
*
* @author Luke
*/
public class StationBoxRenderer implements Painter {
private static final int WAGON_IMAGE_HEIGHT = 10;
private static final int SPACING = 3;
private static final int MAX_WIDTH = 80;
private final ReadOnlyWorld w;
private final Color bgColor;
private final int wagonImageWidth;
private final ModelRoot modelRoot;
private final Image[] cargoImages;
private static final int MAX_HEIGHT = 5 * (WAGON_IMAGE_HEIGHT + SPACING);
public StationBoxRenderer(ReadOnlyWorld world, RenderersRoot vl,
ModelRoot modelRoot) {
this.w = world;
this.bgColor = new Color(0, 0, 200, 60);
this.modelRoot = modelRoot;
// How wide will the wagon images be if we scale them so their height is
// WAGON_IMAGE_HEIGHT?
Image wagonImage = vl.getWagonImages(0).getSideOnImage();
wagonImageWidth = wagonImage.getWidth(null) * WAGON_IMAGE_HEIGHT
/ wagonImage.getHeight(null);
int nrOfCargoTypes = w.size(SKEY.CARGO_TYPES);
cargoImages = new Image[nrOfCargoTypes];
for (int i = 0; i < nrOfCargoTypes; i++) {
String wagonFilename = vl.getWagonImages(i).sideOnFileName;
try {
wagonImage = vl.getScaledImage(wagonFilename,
WAGON_IMAGE_HEIGHT);
} catch (IOException e) {
throw new IllegalArgumentException(wagonFilename);
}
cargoImages[i] = wagonImage;
}
}
public void paint(Graphics2D g) {
Boolean showCargoWaiting = (Boolean) modelRoot
.getProperty(ModelRoot.Property.SHOW_CARGO_AT_STATIONS);
if (showCargoWaiting.booleanValue()) {
/* We only show the station boxes for the current player. */
FreerailsPrincipal principal = modelRoot.getPrincipal();
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
while (wi.next()) { // loop over non null stations
StationModel station = (StationModel) wi.getElement();
int positionX = (station.getStationX() * Constants.TILE_SIZE)
+ Constants.TILE_SIZE / 2;
int positionY = (station.getStationY() * Constants.TILE_SIZE)
+ Constants.TILE_SIZE * 2;
Rectangle r = new Rectangle(positionX, positionY, MAX_WIDTH,
MAX_HEIGHT);
g.setColor(bgColor);
g.fillRect(positionX, positionY, MAX_WIDTH, MAX_HEIGHT);
g.setColor(Color.WHITE);
g.setStroke(new BasicStroke(1f));
g.drawRect(positionX, positionY, MAX_WIDTH, MAX_HEIGHT);
ImmutableCargoBundle cb = (ImmutableCargoBundle) w.get(
principal, KEY.CARGO_BUNDLES, station
.getCargoBundleID());
int[][] carsLoads = calculateCarLoads(cb);
for (int category = 0; category < CargoType
.getNumberOfCategories(); category++) {
int alternateWidth = (MAX_WIDTH - 2 * SPACING)
/ (carsLoads[category].length + 1);
int xOffsetPerWagon = Math.min(wagonImageWidth,
alternateWidth);
for (int car = 0; car < carsLoads[category].length; car++) {
int x = positionX + (car * xOffsetPerWagon)
+ SPACING;
int y = positionY
+ (category * (WAGON_IMAGE_HEIGHT + SPACING));
int cargoType = carsLoads[category][car];
g.drawImage(cargoImages[cargoType], x, y, null);
}
}
}
}
}
/**
* The length of the returned array is the number of complete carloads of
* the specified cargo category in the specified bundle. The values in the
* array are the type of the cargo. E.g. if the bundle contained 2 carloads
* of cargo type 3 and 1 of type 7, {3, 3, 7} would be returned.
*/
private int[][] calculateCarLoads(ImmutableCargoBundle cb) {
int categories = CargoType.getNumberOfCategories();
int numCargoTypes = w.size(SKEY.CARGO_TYPES);
int[] numberOfCarLoads = new int[categories];
int[][] cars = new int[categories][numCargoTypes];
for (int i = 0; i < numCargoTypes; i++) {
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, i);
int carsOfThisCargo = cb.getAmount(i)
/ WagonType.UNITS_OF_CARGO_PER_WAGON;
numberOfCarLoads[ct.getCategory().getNumber()] += carsOfThisCargo;
cars[ct.getCategory().getNumber()][i] += carsOfThisCargo;
}
int[][] returnMatrix = new int[categories][];
for (int category = 0; category < categories; category++) {
int[] returnValue = new int[numberOfCarLoads[category]];
int arrayIndex = 0;
for (int cargoType = 0; cargoType < numCargoTypes; cargoType++) {
for (int j = 0; j < cars[category][cargoType]; j++) {
returnValue[arrayIndex] = cargoType;
arrayIndex++;
}
}
returnMatrix[category] = returnValue;
}
return returnMatrix;
}
}
Methods:
MethodJavadoc
calculateCarLoads/**
paint
jfreerails.client.renderer.StationNamesRenderer
Javadoc:
/** * * Class to render the station names and spheres of influence on the game map. * Names are retrieved from the KEY.STATIONS object. Date: 14th April 2003 28 * May 2004 updated to also show station sphere of influence. * * @author Scott Bennett * @author Luke Lindsay * */
Source code:
/**
*
* Class to render the station names and spheres of influence on the game map.
* Names are retrieved from the KEY.STATIONS object. Date: 14th April 2003 28
* May 2004 updated to also show station sphere of influence.
*
* @author Scott Bennett
* @author Luke Lindsay
*
*/
public class StationNamesRenderer implements Painter {
private final ReadOnlyWorld w;
private final ModelRoot modelRoot;
private final int fontSize;
private final Color bgColor;
private final Color textColor;
final static float[] dash1 = { 5.0f };
final static BasicStroke dashed = new BasicStroke(1.0f,
BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f);
private final Font font;
public StationNamesRenderer(ReadOnlyWorld world, ModelRoot modelRoot) {
this.w = world;
this.modelRoot = modelRoot;
this.fontSize = 10;
this.bgColor = Color.BLACK;
this.textColor = Color.WHITE;
font = new Font("Arial", 0, fontSize);
}
public void paint(Graphics2D g) {
int rectWidth;
int rectHeight;
int rectX;
int rectY;
float visibleAdvance;
float textX;
float textY;
StationModel tempStation;
String stationName;
int positionX;
int positionY;
Boolean showStationNames = (Boolean) modelRoot
.getProperty(ModelRoot.Property.SHOW_STATION_NAMES);
Boolean showStationBorders = (Boolean) modelRoot
.getProperty(ModelRoot.Property.SHOW_STATION_BORDERS);
FontRenderContext frc = g.getFontRenderContext();
TextLayout layout;
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
// draw station names onto map
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
while (wi.next()) { // loop over non null stations
tempStation = (StationModel) wi.getElement();
int x = tempStation.getStationX();
int y = tempStation.getStationY();
// First draw station sphere of influence
if (showStationBorders.booleanValue()) {
FreerailsTile tile = (FreerailsTile) w.getTile(x, y);
int radius = tile.getTrackPiece().getTrackRule().getStationRadius();
int diameterInPixels = (radius * 2 + 1) * 30;
int radiusX = (x - radius) * 30;
int radiusY = (y - radius) * 30;
g.setColor(Color.WHITE);
g.setStroke(dashed);
g.draw(new RoundRectangle2D.Double(radiusX, radiusY,
diameterInPixels, diameterInPixels, 10, 10));
}
// Then draw the station name.
if (showStationNames.booleanValue()) {
stationName = tempStation.getStationName();
positionX = (x * 30) + 15;
positionY = (y * 30) + 30;
layout = new TextLayout(stationName, font, frc);
visibleAdvance = layout.getVisibleAdvance();
rectWidth = (int) (visibleAdvance * 1.2);
rectHeight = (int) (fontSize * 1.5);
rectX = (positionX - (rectWidth / 2));
rectY = positionY;
g.setColor(bgColor);
g.fillRect(rectX, rectY, rectWidth, rectHeight);
textX = (positionX - (visibleAdvance / 2));
textY = positionY + fontSize + 1;
g.setColor(textColor);
layout.draw(g, textX, textY);
g.setStroke(new BasicStroke(1.0f));
// draw a border 1 pixel inside the edges of the rectangle
g.draw(new Rectangle(rectX + 1, rectY + 1, rectWidth - 3,
rectHeight - 3));
}
}
}
// end FOR loop
}
// paint method
}
Methods:
MethodJavadoc
paint
jfreerails.client.renderer.StationRadiusRenderer
Javadoc:
/** * This class draws the radius of a station on the map. * * @author Luke */
Source code:
/**
* This class draws the radius of a station on the map.
*
* @author Luke
*/
public class StationRadiusRenderer implements Painter {
/**
* Border colour to use when placement is OK.
*/
public static final Color COLOR_OK = Color.WHITE;
/**
* Border colour to use when placement is not allowed.
*/
public static final Color COLOR_CANNOT_BUILD = Color.RED;
/**
* Colour of the highlighted border.
*/
private Color borderColor = COLOR_OK;
private static final int tileSize = 30;
private int radius = 2;
private int x;
private int y;
private final ModelRoot modelRoot;
public StationRadiusRenderer(ModelRoot mr) {
this.modelRoot = mr;
}
public void setBorderColor(Color c) {
borderColor = c;
}
public void setPosition(int x, int y) {
this.x = x;
this.y = y;
}
public void setRadius(int radius) {
this.radius = radius;
}
public void show() {
if (!modelRoot
.is(Property.CURSOR_MODE, Value.PLACE_STATION_CURSOR_MODE)) {
modelRoot.setProperty(Property.PREVIOUS_CURSOR_MODE, modelRoot
.getProperty(Property.CURSOR_MODE));
modelRoot.setProperty(Property.CURSOR_MODE,
Value.PLACE_STATION_CURSOR_MODE);
modelRoot.setProperty(Property.IGNORE_KEY_EVENTS, Boolean.TRUE);
}
}
public void hide() {
ModelRoot.Value lastCursorMode = (ModelRoot.Value) modelRoot
.getProperty(ModelRoot.Property.PREVIOUS_CURSOR_MODE);
assert !lastCursorMode
.equals(ModelRoot.Value.PLACE_STATION_CURSOR_MODE);
modelRoot.setProperty(ModelRoot.Property.CURSOR_MODE, lastCursorMode);
modelRoot.setProperty(Property.IGNORE_KEY_EVENTS, Boolean.FALSE);
}
public void paint(Graphics2D g) {
if (modelRoot.getProperty(ModelRoot.Property.CURSOR_MODE).equals(
Value.PLACE_STATION_CURSOR_MODE)) {
g.setStroke(new BasicStroke(2f));
g.setColor(borderColor);
g.drawRect(tileSize * (x - radius), tileSize * (y - radius),
tileSize * (2 * radius + 1), tileSize * (2 * radius + 1));
}
}
}
Methods:
MethodJavadoc
hide
paint
setBorderColor
setPosition
setRadius
show
jfreerails.client.renderer.TileRenderer
Javadoc:
/** * Draws an icon to represent a tile. * * @author Luke Lindsay * */
Source code:
/**
* Draws an icon to represent a tile.
*
* @author Luke Lindsay
*
*/
public interface TileRenderer {
Image getDefaultIcon();
void renderTile(java.awt.Graphics g, int renderX, int renderY, int mapX,
int mapY, ReadOnlyWorld w);
/** Adds the images this TileRenderer uses to the specified ImageManager. */
void dumpImages(ImageManager imageManager);
}
Methods:
MethodJavadoc
dumpImages/** Adds the images this TileRenderer uses to the specified ImageManager. */
getDefaultIcon
renderTile
jfreerails.client.renderer.TileRendererList
Javadoc:
/** * A list of TileRenderers. * * @author Luke Lindsay 09 October 2001 */
Source code:
/**
* A list of TileRenderers.
*
* @author Luke Lindsay 09 October 2001
*/
public interface TileRendererList {
TileRenderer getTileViewWithNumber(int i);
/**
* Checks whether this tile view list has tile views for all the terrain
* types in the specified list.
*/
boolean validate(ReadOnlyWorld world);
}
Methods:
MethodJavadoc
getTileViewWithNumber
validate/**
jfreerails.client.renderer.TileRendererListImpl
Javadoc:
/** * A list of TileRenderers stored in an array and created from an ArrayList. * * @author Luke Lindsay 09 October 2001 */
Source code:
/**
* A list of TileRenderers stored in an array and created from an ArrayList.
*
* @author Luke Lindsay 09 October 2001
*/
final public class TileRendererListImpl implements TileRendererList {
private final TileRenderer[] tiles;
public TileRenderer getTileViewWithNumber(int i) {
return tiles[i];
}
public TileRendererListImpl(ArrayList<TileRenderer> t) {
tiles = new TileRenderer[t.size()];
for (int i = 0; i < t.size(); i++) {
tiles[i] = t.get(i);
}
}
public boolean validate(ReadOnlyWorld w) {
// There should a TileRenderer for each terrain type.
return w.size(SKEY.TERRAIN_TYPES) == tiles.length;
}
}
Methods:
MethodJavadoc
getTileViewWithNumber
validate
jfreerails.client.renderer.TrackPieceRenderer
Javadoc:
/** * Draws an icon to represent a track piece. * * @author Luke Lindsay 09 October 2001 */
Source code:
/**
* Draws an icon to represent a track piece.
*
* @author Luke Lindsay 09 October 2001
*/
public interface TrackPieceRenderer {
Image getTrackPieceIcon(int trackTemplate);
void drawTrackPieceIcon(int trackTemplate, java.awt.Graphics g, int x,
int y, java.awt.Dimension tileSize);
/** Adds the images this TileRenderer uses to the specified ImageManager. */
void dumpImages(ImageManager imageManager);
}
Methods:
MethodJavadoc
drawTrackPieceIcon
dumpImages/** Adds the images this TileRenderer uses to the specified ImageManager. */
getTrackPieceIcon
jfreerails.client.renderer.TrackPieceRendererImpl
Javadoc:
/** * This class renders a track piece. * * @author Luke Lindsay 09 October 2001 */
Source code:
/**
* This class renders a track piece.
*
* @author Luke Lindsay 09 October 2001
*/
final public class TrackPieceRendererImpl implements TrackPieceRenderer {
private final Image[] trackPieceIcons = new Image[512];
private final String typeName;
public void drawTrackPieceIcon(int trackTemplate, java.awt.Graphics g,
int x, int y, java.awt.Dimension tileSize) {
if ((trackTemplate > 511) || (trackTemplate < 0)) {
throw new java.lang.IllegalArgumentException("trackTemplate = "
+ trackTemplate + ", it should be in the range 0-511");
}
if (trackPieceIcons[trackTemplate] != null) {
int drawX = x * tileSize.width - tileSize.width / 2;
int drawY = y * tileSize.height - tileSize.height / 2;
g.drawImage(trackPieceIcons[trackTemplate], drawX, drawY, null);
}
}
public TrackPieceRendererImpl(ReadOnlyWorld w, ImageManager imageManager,
int typeNumber) throws IOException {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, typeNumber);
this.typeName = trackRule.getTypeName();
for (int i = 0; i < 512; i++) {
if (trackRule.testTrackPieceLegality(i)) {
String fileName = generateFilename(i, getTrackTypeName());
trackPieceIcons[i] = imageManager.getImage(fileName);
}
}
}
public Image getTrackPieceIcon(int trackTemplate) {
if ((trackTemplate > 511) || (trackTemplate < 0)) {
throw new java.lang.IllegalArgumentException("trackTemplate = "
+ trackTemplate + ", it should be in the range 0-511");
}
return trackPieceIcons[trackTemplate];
}
public void dumpImages(ImageManager imageManager) {
for (int i = 0; i < 512; i++) {
if (trackPieceIcons[i] != null) {
String fileName = generateFilename(i, getTrackTypeName());
imageManager.setImage(fileName, trackPieceIcons[i]);
}
}
}
public static String generateFilename(int i, String trackTypeName) {
String relativeFileNameBase = "track" + File.separator + trackTypeName;
int newTemplate = TrackConfiguration.from9bitTemplate(i)
.get8bitTemplate();
String fileName = relativeFileNameBase + "_"
+ BinaryNumberFormatter.formatWithLowBitOnLeft(newTemplate, 8)
+ ".png";
return fileName;
}
private String getTrackTypeName() {
return typeName;
}
}
Methods:
MethodJavadoc
drawTrackPieceIcon
dumpImages
generateFilename
getTrackPieceIcon
getTrackTypeName
jfreerails.client.renderer.TrackPieceRendererList
Javadoc:
/** * A list of TrackPieceRenderers. * * @author Luke */
Source code:
/**
* A list of TrackPieceRenderers.
*
* @author Luke
*/
final public class TrackPieceRendererList {
private static final Logger logger = Logger
.getLogger(TrackPieceRendererList.class.getName());
private final TrackPieceRenderer[] trackPieceViewArray;
public TrackPieceRenderer getTrackPieceView(int i) {
if (NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER == i) {
return NullTrackPieceRenderer.instance;
}
return trackPieceViewArray[i];
}
public TrackPieceRendererList(ReadOnlyWorld w, ImageManager imageManager,
FreerailsProgressMonitor pm) throws IOException {
// Setup progress monitor..
pm.nextStep(w.size(SKEY.TRACK_RULES));
int progress = 0;
pm.setValue(progress);
int numberOfTrackTypes = w.size(SKEY.TRACK_RULES);
trackPieceViewArray = new TrackPieceRenderer[numberOfTrackTypes];
for (int i = 0; i < numberOfTrackTypes; i++) {
trackPieceViewArray[i] = new TrackPieceRendererImpl(w,
imageManager, i);
pm.setValue(++progress);
}
}
public boolean validate(ReadOnlyWorld w) {
boolean okSoFar = true;
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
Iterator<TrackConfiguration> legalConfigurationsIterator = trackRule
.getLegalConfigurationsIterator();
TrackPieceRenderer trackPieceView = this.getTrackPieceView(i);
if (null == trackPieceView) {
logger
.warning("No track piece view for the following track type: "
+ trackRule.getTypeName());
return false;
}
while (legalConfigurationsIterator.hasNext()) {
TrackConfiguration trackConfig = legalConfigurationsIterator
.next();
int trackGraphicsNo = trackConfig.getTrackGraphicsID();
Image img = trackPieceView.getTrackPieceIcon(trackGraphicsNo);
if (null == img) {
logger
.warning("No track piece image for the following track type: "
+ trackRule.getTypeName()
+ ", with configuration: "
+ trackGraphicsNo);
okSoFar = false;
}
}
}
return okSoFar;
}
}
Methods:
MethodJavadoc
getTrackPieceView
validate
jfreerails.client.renderer.TrainImages
Javadoc:
/** * Stores side-on and over-head images of a particular wagon or engine type. * * @author Luke * * */
Source code:
/**
* Stores side-on and over-head images of a particular wagon or engine type.
*
* @author Luke
*
*
*/
public class TrainImages {
public enum Highlight{SELECTED, FOCUSED};
private final Image sideOnImage;
private final Image[] overheadImages = new Image[8];
private final Image[] overheadSelectedImages = new Image[8];
private final Image[] overheadFocusedImages = new Image[8];
public final String sideOnFileName;
public Image getSideOnImage() {
return sideOnImage;
}
public Image getOverheadImage(int direction) {
return overheadImages[direction];
}
/**
* @param direction
* @return the image to render under the wagon/engine image
* when the train is selects/focused.
*/
public Image getOverheadHighlightImage(int direction, Highlight h) {
if(h == Highlight.FOCUSED)
return overheadFocusedImages[direction];
if(h == Highlight.SELECTED)
return overheadSelectedImages[direction];
return null;
}
public static String generateOverheadFilename(String name, int i) {
Step[] vectors = Step.getList();
return "trains" + File.separator + "overhead" + File.separator + name
+ "_" + vectors[i].toAbrvString() + ".png";
}
public static String generateSideOnFilename(String name) {
return "trains" + File.separator + "sideon" + File.separator + name
+ ".png";
}
public TrainImages(ImageManager imageManager, String name) throws IOException {
sideOnFileName = TrainImages.generateSideOnFilename(name);
sideOnImage = imageManager.getImage(sideOnFileName);
for (int direction = 0; direction < 8; direction++) {
overheadImages[direction] = imageManager
.getImage(generateOverheadFilename(name, direction));
overheadSelectedImages[direction] = imageManager
.getImage(generateOverheadFilename("highlights" + File.separator + "selected", direction));
overheadFocusedImages[direction] = imageManager
.getImage(generateOverheadFilename("highlights" + File.separator + "focused", direction));
}
}
}
Methods:
MethodJavadoc
generateOverheadFilename
generateSideOnFilename/**
getOverheadHighlightImage/**
getOverheadImage
getSideOnImage
jfreerails.client.renderer.TrainRenderer
Javadoc:
/** * This class draws a train from an overhead view. * * Also has a method that determines if a mouse click was on a train. * * @author Luke Lindsay 13-Oct-2002 * */
Source code:
/**
* This class draws a train from an overhead view.
*
* Also has a method that determines if a mouse click was on a train.
*
* @author Luke Lindsay 13-Oct-2002
*
*/
public class TrainRenderer {
private final RenderersRoot rr;
public TrainRenderer(RenderersRoot trainImages) {
this.rr = trainImages;
}
/**
* Calculates the positions of the engine and each wagon on the map.
* Intended to be used for rendering trains, for rendering highlights
* around trains, and for determining if a mouse click was on a train.
*
* @param train
* @param s
* @return List of positions, one entry for the engine and one for each
* wagon.
*/
public List<Entry<Point, Step>> calcPositions(TrainModel train, TrainPositionOnMap s) {
List<Entry<Point, Step>> positions = new ArrayList<>(train.getLength() + 1);
FreerailsPathIterator it = s.path();
PathWalker pw = new PathWalkerImpl(it);
// Engine + wagons
for (int i = 0; i < train.getNumberOfWagons() + 1; i++) {
IntLine wagon = new IntLine();
IntLine line = new IntLine();
pw.stepForward(16);
boolean firstIteration = true;
while (pw.hasNext()) {
pw.nextSegment(line);
if (firstIteration) {
wagon.x1 = line.x1;
wagon.y1 = line.y1;
firstIteration = false;
}
}
wagon.x2 = line.x2;
wagon.y2 = line.y2;
Step v = Step
.getNearestVector(wagon.x2 - wagon.x1, wagon.y2 - wagon.y1);
Point wagonCenter = new Point((wagon.x2 + wagon.x1) / 2,
(wagon.y2 + wagon.y1) / 2);
positions.add(new AbstractMap.SimpleImmutableEntry<>(wagonCenter, v));
// The gap between wagons
pw.stepForward(8);
while (pw.hasNext()) {
pw.nextSegment(line);
}
}
return positions;
}
public void paintTrain(Graphics g, TrainModel train, List<Entry<Point, Step>> positions) {
for (int i = 0; i < positions.size(); i++) {
TrainImages trainImages;
if (i == 0) {
trainImages = rr.getEngineImages(train.getEngineType());
} else {
int type = train.getWagon(i - 1);
trainImages = rr.getWagonImages(type);
}
Entry<Point, Step> entry = positions.get(i);
Image image = trainImages.getOverheadImage(entry.getValue().getID());
Point p = entry.getKey();
g.drawImage(image, p.x - 15, p.y - 15, null);
}
}
public void paintTrainHighlight(Graphics g, TrainModel train, List<Entry<Point, Step>> positions, TrainImages.Highlight highlight) {
for (int i = 0; i < positions.size(); i++) {
TrainImages trainImages;
if (i == 0) {
trainImages = rr.getEngineImages(train.getEngineType());
} else {
int type = train.getWagon(i - 1);
trainImages = rr.getWagonImages(type);
}
Entry<Point, Step> entry = positions.get(i);
Image image = trainImages.getOverheadHighlightImage(entry.getValue().getID(), highlight);
Point p = entry.getKey();
g.drawImage(image, p.x - 15, p.y - 15, null);
}
}
public boolean isHit(Point mousePosition, TrainModel train, List<Entry<Point, Step>> positions) {
for (int i = 0; i < positions.size(); i++) {
Entry<Point, Step> entry = positions.get(i);
Point p = entry.getKey();
int xDist = mousePosition.x - p.x;
int yDist = mousePosition.y - p.y;
int sumSquares = xDist * xDist + yDist * yDist;
if( sumSquares > 15 * 15){
continue;
}
TrainImages trainImages;
if (i == 0) {
trainImages = rr.getEngineImages(train.getEngineType());
} else {
int type = train.getWagon(i - 1);
trainImages = rr.getWagonImages(type);
}
BufferedImage image = (BufferedImage) trainImages.getOverheadImage(entry.getValue().getID());
int x = xDist + 15;
int y = yDist + 15;
Color c = new Color(image.getRGB(x, y), true);
int alpha = c.getAlpha();
if(alpha > 128){
return true;
}
}
return false;
}
public void paintTrain(Graphics g, TrainModel train, TrainPositionOnMap s, TrainImages.Highlight highlight) {
// If the train has been removed, it will be null!
if (train == null) {
return;
}
/*
* XXX HACK !! really our position ought to be defined at all times, but
* this is a workaround until we can fix movement
*/
if (s == null) {
return;
}
List<Entry<Point, Step>> positions = calcPositions(train, s);
if(null != highlight){
paintTrainHighlight(g, train, positions, highlight);
}
paintTrain(g, train, positions);
}
// @SonnyZ
// This code renders the explosion that occurs when 2 trains crash on the
// map
public void paintTrainCrash(Graphics g, TrainPositionOnMap s) {
// check to see if there is a train
// if (s == null) {
// return;
// }
// // Get the image for that frame of the explosion
// Image explosionImage = rr
// .getExplosionImage(s.getFrameCt() - 1);
// // draw the image
// for (int i = 0; i < s.getLength() - 1; i++) {
// Point wagonCenter = new Point(s.getX(i), s.getY(i));
// g.drawImage(explosionImage, wagonCenter.x - 15, wagonCenter.y - 15, null);
//
// }
// // increment the frame count
// s.incrementFramCt();
}
}
Methods:
MethodJavadoc
calcPositions/**
isHit
paintTrain
paintTrain
paintTrainCrash
paintTrainHighlight
jfreerails.client.renderer.ZoomedOutMapRenderer
Javadoc:
/** * This class draws the overview map. * * @author Luke Lindsay * @author Robert Tuck */
Source code:
/**
* This class draws the overview map.
*
* @author Luke Lindsay
* @author Robert Tuck
*/
final public class ZoomedOutMapRenderer implements MapRenderer {
private final int imageWidth;
private final int imageHeight;
private final int mapWidth;
private final int mapHeight;
private final int mapX;
private final int mapY;
private final ReadOnlyWorld w;
private BufferedImage one2oneImage;
private BufferedImage mapImage;
private final AffineTransform affineTransform;
// private Graphics2D mapGraphics;
private final GraphicsConfiguration defaultConfiguration = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
private boolean isDirty = true;
public static ZoomedOutMapRenderer getInstance(ReadOnlyWorld world,
Dimension maxSize) {
// Work with doubles to avoid rounding errors.
double worldWidth = world.getMapWidth();
double worldHeight = world.getMapHeight();
double scale;
if (worldWidth / worldHeight > maxSize.getWidth() / maxSize.getHeight()) {
scale = maxSize.getWidth() / worldWidth;
} else {
scale = maxSize.getHeight() / worldHeight;
}
double height = scale * worldHeight;
double width = scale * worldWidth;
return new ZoomedOutMapRenderer(world, (int) width, (int) height, 0, 0,
world.getMapWidth(), world.getMapHeight());
}
private ZoomedOutMapRenderer(ReadOnlyWorld world, int width, int height,
int mapX, int mapY, int mapWidth, int mapHeight) {
w = world;
this.mapWidth = mapWidth;
this.mapHeight = mapHeight;
imageHeight = height;
imageWidth = width;
double scalingFactor = ((double) imageHeight) / mapHeight;
affineTransform = AffineTransform.getScaleInstance(scalingFactor,
scalingFactor);
this.mapX = mapX;
this.mapY = mapY;
refresh();
}
public float getScale() {
return (float) imageHeight / (float) mapHeight;
}
public void paintRect(Graphics g, Rectangle visibleRect) {
renderOffScreenImage();
g.drawImage(mapImage, 0, 0, null);
}
private void renderOffScreenImage() {
if (isDirty) {
Graphics2D mapGraphics = mapImage.createGraphics();
mapGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
mapGraphics.setClip(0, 0, imageWidth, imageHeight);
mapGraphics.clearRect(0, 0, imageWidth, imageHeight);
mapGraphics.drawImage(one2oneImage, affineTransform, null);
isDirty = false;
}
}
private void refreshTile(Point tile) {
FreerailsTile tt = (FreerailsTile) w.getTile(tile.x, tile.y);
if (tt.getTrackPiece().equals(NullTrackPiece.getInstance())) {
int typeNumber = tt.getTerrainTypeID();
TerrainType terrainType = (TerrainType) w.get(SKEY.TERRAIN_TYPES,
typeNumber);
one2oneImage.setRGB(tile.x, tile.y, terrainType.getRGB());
} else {
/* black with alpha of 1 */
one2oneImage.setRGB(tile.x, tile.y, 0xff000000);
}
isDirty = true;
// int scaledX = (tile.x - mapX) * imageWidth / mapWidth;
// int scaledY = (tile.y - mapY) * imageHeight / mapHeight;
// int minx = scaledX < 2 ? 0 : scaledX - 2;
// int miny = scaledY < 2 ? 0 : scaledY - 2;
// int maxx = scaledX > imageWidth - 4 ? imageWidth : scaledX + 4;
// int maxy = scaledY > imageHeight - 4 ? imageHeight : scaledY + 4;
// mapGraphics.setClip(minx, miny, maxx - minx, maxy - miny);
// mapGraphics.clearRect(minx, miny, maxx - minx, maxy - miny);
// mapGraphics.drawImage(one2oneImage, affineTransform, null);
}
/**
* Redraw the whole map onto a new buffer.
*/
private void refresh() {
isDirty = true;
/* free up memory used by the old image */
if (mapImage != null) {
mapImage.flush();
}
if (one2oneImage != null) {
one2oneImage.flush();
}
// if (mapGraphics != null) {
// mapGraphics.dispose();
// }
/* generate a 1:1 map of the terrain layer */
one2oneImage = defaultConfiguration.createCompatibleImage(mapWidth,
mapHeight, Transparency.TRANSLUCENT);
mapImage = defaultConfiguration.createCompatibleImage(imageWidth,
imageHeight, Transparency.OPAQUE);
Point tile = new Point();
for (tile.x = mapX; tile.x < mapWidth + mapX; tile.x++) {
for (tile.y = mapY; tile.y < mapHeight + mapY; tile.y++) {
FreerailsTile tt = (FreerailsTile) w.getTile(tile.x, tile.y);
if (tt.getTrackPiece().equals(NullTrackPiece.getInstance())) {
int typeNumber = tt.getTerrainTypeID();
TerrainType terrainType = (TerrainType) w.get(
SKEY.TERRAIN_TYPES, typeNumber);
one2oneImage.setRGB(tile.x - mapX, tile.y - mapY,
terrainType.getRGB());
} else {
/* black with alpha of 1 */
one2oneImage.setRGB(tile.x - mapX, tile.y - mapY,
0xff000000);
}
}
}
renderOffScreenImage();
}
/*
* @see NewMapView#getMapSizeInPixels()
*/
public Dimension getMapSizeInPixels() {
return new Dimension(imageWidth, imageHeight);
}
public void paintTile(Graphics g, int tileX, int tileY) {
g.drawImage(mapImage, 0, 0, null);
}
public void refreshTile(int x, int y) {
refreshTile(new Point(x, y));
}
public void refreshAll() {
refresh();
}
}
Methods:
MethodJavadoc
getInstance
getMapSizeInPixels
getScale/**
paintRect
paintTile
refresh/**
refreshAll
refreshTile
refreshTile
renderOffScreenImage
jfreerails.client.top.BuildIndustryJPopupMenu
Javadoc:
/** * A JPopupMenu that displays the list of industries that can be built. This * class contains the code that generates and dispatches a ChangeTileMove when * the player clicks on the menu. * * @author Luke * */
Source code:
/**
* A JPopupMenu that displays the list of industries that can be built. This
* class contains the code that generates and dispatches a ChangeTileMove when
* the player clicks on the menu.
*
* @author Luke
*
*/
public class BuildIndustryJPopupMenu extends JPopupMenu implements View {
private static final long serialVersionUID = 3689636912575165749L;
private final Point cursorLocation = new Point();
public void setCursorLocation(Point p) {
cursorLocation.x = p.x;
cursorLocation.y = p.y;
}
public void setup(final ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
this.removeAll();
final NonNullElements it = new NonNullElements(SKEY.TERRAIN_TYPES,
modelRoot.getWorld());
while (it.next()) {
TerrainType type = (TerrainType) it.getElement();
final Money price = type.getBuildCost();
if (null != price) {
JMenuItem item = new JMenuItem(type.getDisplayName() + " "
+ price);
item.addActionListener(new ActionListener() {
private final int terrainType = it.getIndex();
public void actionPerformed(ActionEvent arg0) {
Move m1 = new ChangeTileMove(modelRoot.getWorld(),
cursorLocation, terrainType);
Transaction t = new AddItemTransaction(
Transaction.Category.INDUSTRIES, terrainType,
1, price.changeSign());
Move m2 = new AddTransactionMove(modelRoot
.getPrincipal(), t);
CompositeMove m3 = new CompositeMove(m1, m2);
MoveStatus ms = modelRoot.doMove(m3);
if (!ms.ok) {
modelRoot.setProperty(
ModelRoot.Property.CURSOR_MESSAGE,
ms.message);
}
}
});
add(item);
}
}
}
}
Methods:
MethodJavadoc
setCursorLocation
setup
jfreerails.client.top.BuildMenu
Javadoc:
/** * The menu that lets you select a track type. * * @author Luke Lindsay */
Source code:
/**
* The menu that lets you select a track type.
*
* @author Luke Lindsay
*/
final public class BuildMenu extends javax.swing.JMenu {
private static final long serialVersionUID = 3617850859305055542L;
public BuildMenu() {
super();
}
public void setup(ActionRoot actionRoot) {
this.removeAll();
this.setText("Build");
add(actionRoot.getBuildTrainDialogAction());
}
}
Methods:
MethodJavadoc
setup
jfreerails.client.top.ClientJFrame
Javadoc:
/** * The JFrame that you see while you are playing the game. * * @author Luke */
Source code:
/**
* The JFrame that you see while you are playing the game.
*
* @author Luke
*/
public class ClientJFrame extends javax.swing.JFrame {
private static final long serialVersionUID = 3834868100742265142L;
private GUIComponentFactory gUIComponentFactory;
/** Creates new form ClientJFrame. */
public ClientJFrame(GUIComponentFactory gcf) {
setup(gcf);
}
private void setup(GUIComponentFactory gcf) {
this.gUIComponentFactory = gcf;
initComponents();
gUIComponentFactory.createDateJLabel();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
rhsjPanel = new javax.swing.JPanel();
mapOverview = gUIComponentFactory.createOverviewMap();
trainsJTabPane1 = gUIComponentFactory.createTrainsJTabPane();
lhsjPanel = new javax.swing.JPanel();
mainMapView = gUIComponentFactory.createMainMap();
statusjPanel = new javax.swing.JPanel();
datejLabel = gUIComponentFactory.createDateJLabel();
cashjLabel = gUIComponentFactory.createCashJLabel();
jMenuBar1 = new javax.swing.JMenuBar();
gameMenu = gUIComponentFactory.createGameMenu();
buildMenu = gUIComponentFactory.createBuildMenu();
BrokerMenu1 = gUIComponentFactory.createBrokerMenu();
displayMenu = gUIComponentFactory.createDisplayMenu();
reportsMenu = gUIComponentFactory.createReportsMenu();
helpMenu = gUIComponentFactory.createHelpMenu();
getContentPane().setLayout(new java.awt.GridBagLayout());
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
rhsjPanel.setLayout(new java.awt.GridBagLayout());
rhsjPanel.add(mapOverview, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
rhsjPanel.add(trainsJTabPane1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
getContentPane().add(rhsjPanel, gridBagConstraints);
lhsjPanel.setLayout(new java.awt.GridBagLayout());
mainMapView.setAlignmentX(0.0F);
mainMapView.setAlignmentY(0.0F);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
lhsjPanel.add(mainMapView, gridBagConstraints);
statusjPanel.add(datejLabel);
statusjPanel.add(cashjLabel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
lhsjPanel.add(statusjPanel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(lhsjPanel, gridBagConstraints);
gameMenu.setText("Game");
jMenuBar1.add(gameMenu);
buildMenu.setText("Build");
jMenuBar1.add(buildMenu);
BrokerMenu1.setText("Broker");
jMenuBar1.add(BrokerMenu1);
displayMenu.setText("Display");
jMenuBar1.add(displayMenu);
reportsMenu.setText("Reports");
jMenuBar1.add(reportsMenu);
helpMenu.setText("Help");
jMenuBar1.add(helpMenu);
setJMenuBar(jMenuBar1);
pack();
}// GEN-END:initComponents
/** Exit the Application. */
private void exitForm(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_exitForm
System.exit(0);
}// GEN-LAST:event_exitForm
public static void main(String args[]) {
new ClientJFrame(new GUIComponentFactoryTestImpl()).setVisible(true);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu BrokerMenu1;
private javax.swing.JMenu buildMenu;
private javax.swing.JLabel cashjLabel;
private javax.swing.JLabel datejLabel;
private javax.swing.JMenu displayMenu;
private javax.swing.JMenu gameMenu;
private javax.swing.JMenu helpMenu;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel lhsjPanel;
private javax.swing.JScrollPane mainMapView;
private javax.swing.JPanel mapOverview;
private javax.swing.JMenu reportsMenu;
private javax.swing.JPanel rhsjPanel;
private javax.swing.JPanel statusjPanel;
private javax.swing.JTabbedPane trainsJTabPane1;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
exitForm/** Exit the Application. */
initComponents/**
main
setup
jfreerails.client.top.FPScounter
Javadoc:
/** * Provides a method that draws a String showing the average FPS over the last * complete 5000ms interval. * * @author Luke * */
Source code:
/**
* Provides a method that draws a String showing the average FPS over the last
* complete 5000ms interval.
*
* @author Luke
*
*/
public class FPScounter {
private final double[] fpsValues = new double[400];
private int newFrameCount = 0;
private String newFPSstr = "starting..";
private long lastFrameTime;
private final int fontSize;
private final Color bgColor;
FPScounter() {
this.fontSize = 10;
bgColor = new Color(0, 0, 128);
}
// Display the average number of FPS.
void updateFPSCounter() {
long currentTime = System.nanoTime();
if (newFrameCount == 0) {
lastFrameTime = currentTime;
}
double dt = currentTime - lastFrameTime;
double fps = 1000000000d / dt;
fpsValues[newFrameCount % fpsValues.length] = fps;
newFrameCount++;
int n = fpsValues.length;
if (newFrameCount > fpsValues.length) {
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
double mean = 0;
for (int i = 0; i < fpsValues.length; i++) {
min = Math.min(min, fpsValues[i]);
max = Math.max(max, fpsValues[i]);
mean += fpsValues[i];
}
mean = mean / n;
if (mean > max)
throw new IllegalStateException();
if (mean < min)
throw new IllegalStateException();
double variance = 0;
for (int i = 0; i < fpsValues.length; i++) {
double xMinusU = fpsValues[i] - mean;
variance += xMinusU * xMinusU;
}
variance = variance / n;
if (newFrameCount % 20 == 0) {
StringBuffer sb = new StringBuffer();
sb.append("FPS\n");
sb.append(" n ");
sb.append(n);
sb.append('\n');
sb.append(" \u03BC ");
sb.append(Math.round(mean));
sb.append('\n');
sb.append(" \u03C3 ");
sb.append(Math.round(Math.sqrt(variance)));
sb.append('\n');
sb.append(" min ");
sb.append(Math.round(min));
sb.append('\n');
sb.append(" max ");
sb.append(Math.round(max));
sb.append('\n');
newFPSstr = sb.toString();
}
}
// g.setColor(Color.WHITE);
// g.fillRect(50, 50, 50, 20);
// g.setColor(Color.BLACK);
// g.drawString(newFPSstr, 50, 65);
lastFrameTime = currentTime;
}
void drawFPS(Graphics2D g) {
int rectWidth;
int rectHeight;
int rectX;
int rectY;
int positionX = 50;
int positionY = 70;
Color textColor = Color.WHITE;
String[] lines = newFPSstr.split("\n");
rectWidth = 60;
rectHeight = (int) ((fontSize + 1) * 1.2 * lines.length);
rectY = (int) (positionY - fontSize * 1.2);
rectX = positionX;
g.setColor(bgColor);
g.fillRect(rectX, rectY, rectWidth, rectHeight);
g.setColor(textColor);
// g.setFont(font);
for (String s : lines) {
g.drawString(s, positionX, positionY);
positionY += fontSize * 1.2;
}
}
}
Methods:
MethodJavadoc
drawFPS
updateFPSCounter
jfreerails.client.top.GUIComponentFactory
Javadoc:
/** * Defines methods that create the GUI components used by the game. * * @author Luke */
Source code:
/**
* Defines methods that create the GUI components used by the game.
*
* @author Luke
*/
public interface GUIComponentFactory {
JPanel createOverviewMap();
JTabbedPane createTrainsJTabPane();
JScrollPane createMainMap();
JLabel createCashJLabel();
JLabel createDateJLabel();
JMenu createBuildMenu();
JMenu createReportsMenu();
JMenu createGameMenu();
JMenu createDisplayMenu();
JMenu createHelpMenu();
JMenu createBrokerMenu();
}
Methods:
MethodJavadoc
createBrokerMenu
createBuildMenu
createCashJLabel
createDateJLabel
createDisplayMenu
createGameMenu
createHelpMenu
createMainMap
createOverviewMap
createReportsMenu
createTrainsJTabPane
jfreerails.client.top.GUIComponentFactoryImpl
Javadoc:
/** * Creates and wires up the GUI components. * * @author Luke */
Source code:
/**
* Creates and wires up the GUI components.
*
* @author Luke
*/
public class GUIComponentFactoryImpl implements GUIComponentFactory,
WorldMapListener, WorldListListener {
/** Whether to show certain 'cheat' menus used for testing. */
private static final boolean CHEAT = (System.getProperty("cheat") != null);
private static final Logger logger = Logger
.getLogger(GUIComponentFactoryImpl.class.getName());
private final ActionRoot actionRoot;
private final BuildMenu buildMenu;
private final CashJLabel cashjLabel;
private final ClientJFrame clientJFrame;
private final DateJLabel datejLabel;
private final DialogueBoxController dialogueBoxController;
private JMenu displayMenu;
private JMenu helpMenu;
private JMenu brokerMenu;
private boolean isSetup = false;
private JMenuItem leaderBoardJMenuItem;
private DetailMapRenderer mainMap;
private final JScrollPane mainMapScrollPane1;
private final MapViewJComponentConcrete mapViewJComponent;
private final ModelRootImpl modelRoot;
private JMenuItem networthGraphJMenuItem;
private MapRenderer overviewMap;
private final JPanel overviewMapContainer;
private final Rectangle r = new Rectangle(10, 10, 10, 10);
private JMenu reportsMenu;
private ServerControlModel sc;
private ActionAdapter speedActions;
private JMenuItem stationInfoJMenuItem;
private final StationTypesPopup stationTypesPopup;
private JMenuItem trainListJMenuItem;
private JMenuItem trainOrdersJMenuItem;
private JMenuItem callBrokerJMenuItem;
/**
* This is the panel at the bottom right of the screen.
*/
private final RHSJTabPane trainsJTabPane;
private final UserInputOnMapController userInputOnMapController;
private UserMessageGenerator userMessageGenerator;
private RenderersRoot renderers;
private ReadOnlyWorld world;
public GUIComponentFactoryImpl(ModelRootImpl mr, ActionRoot ar) {
modelRoot = mr;
actionRoot = ar;
userInputOnMapController = new UserInputOnMapController(modelRoot, ar);
buildMenu = new jfreerails.client.top.BuildMenu();
mapViewJComponent = new MapViewJComponentConcrete();
mainMapScrollPane1 = new JScrollPane();
overviewMapContainer = new OverviewMapJComponent(r);
stationTypesPopup = new StationTypesPopup();
MainMapAndOverviewMapMediator mediator = new MainMapAndOverviewMapMediator();
mediator.setup(overviewMapContainer, mainMapScrollPane1.getViewport(),
mapViewJComponent, r);
trainsJTabPane = new RHSJTabPane();
datejLabel = new DateJLabel();
cashjLabel = new CashJLabel();
clientJFrame = new ClientJFrame(this);
dialogueBoxController = new DialogueBoxController(clientJFrame,
modelRoot);
actionRoot.setDialogueBoxController(dialogueBoxController);
modelRoot.addSplitMoveReceiver(new MoveReceiver() {
public void processMove(Move move) {
if (move instanceof ChangeGameSpeedMove) {
ChangeGameSpeedMove speedMove = (ChangeGameSpeedMove) move;
for (Enumeration<Action> actionsEnum = speedActions
.getActions(); actionsEnum.hasMoreElements();) {
Action action = actionsEnum.nextElement();
String actionName = (String) action
.getValue(Action.NAME);
if (actionName.equals(actionRoot.getServerControls()
.getGameSpeedDesc(speedMove.getNewSpeed()))) {
speedActions.setSelectedItem(actionName);
}
break;
}
}
}
});
userMessageGenerator = new UserMessageGenerator(this.modelRoot,
this.actionRoot);
modelRoot.addCompleteMoveReceiver(userMessageGenerator);
}
private void countStations() {
NonNullElements stations = new NonNullElements(KEY.STATIONS, modelRoot
.getWorld(), modelRoot.getPrincipal());
boolean enabled;
if (stations.size() > 0) {
enabled = true;
} else {
enabled = false;
}
this.trainsJTabPane.setStationTabEnabled(enabled);
this.stationInfoJMenuItem.setEnabled(enabled);
}
private void countTrains() {
NonNullElements trains = new NonNullElements(KEY.TRAINS, modelRoot
.getWorld(), modelRoot.getPrincipal());
boolean enabled;
if (trains.size() > 0) {
enabled = true;
} else {
enabled = false;
}
this.trainsJTabPane.setTrainTabEnabled(enabled);
this.trainListJMenuItem.setEnabled(enabled);
this.trainOrdersJMenuItem.setEnabled(enabled);
}
public JMenu createBuildMenu() {
return buildMenu;
}
public JLabel createCashJLabel() {
return cashjLabel;
}
public JFrame createClientJFrame(String title) {
clientJFrame.setTitle(title);
return clientJFrame;
}
public JLabel createDateJLabel() {
return datejLabel;
}
public JMenu createBrokerMenu() {
brokerMenu = new JMenu("Broker");
callBrokerJMenuItem = new JMenuItem("Call Broker");
callBrokerJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showBrokerScreen();
}
});
brokerMenu.add(callBrokerJMenuItem);
return brokerMenu;
}
public JMenu createDisplayMenu() {
displayMenu = new JMenu("Display");
displayMenu.setMnemonic(68);
trainOrdersJMenuItem = new JMenuItem("Train Orders");
trainOrdersJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showTrainOrders();
}
});
stationInfoJMenuItem = new JMenuItem("Station Info");
stationInfoJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showStationInfo(0);
}
});
trainListJMenuItem = new JMenuItem("Train List");
trainListJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showTrainList();
}
});
displayMenu.add(trainOrdersJMenuItem);
displayMenu.add(stationInfoJMenuItem);
displayMenu.add(trainListJMenuItem);
displayMenu.addSeparator();
// Add menu items to control what gets displayed on the map.
final JCheckBoxMenuItem showCargoMenuItem = new JCheckBoxMenuItem(
"Show cargo at stations", true);
displayMenu.add(showCargoMenuItem);
showCargoMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modelRoot.setProperty(
ModelRoot.Property.SHOW_CARGO_AT_STATIONS, new Boolean(
showCargoMenuItem.isSelected()));
mapViewJComponent.refreshAll();
}
});
final JCheckBoxMenuItem showStationNamesMenuItem = new JCheckBoxMenuItem(
"Show station names", true);
displayMenu.add(showStationNamesMenuItem);
showStationNamesMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modelRoot.setProperty(ModelRoot.Property.SHOW_STATION_NAMES,
new Boolean(showStationNamesMenuItem.isSelected()));
mapViewJComponent.refreshAll();
}
});
final JCheckBoxMenuItem showStationBordersMenuItem = new JCheckBoxMenuItem(
"Show sphere-of-influence around stations", true);
displayMenu.add(showStationBordersMenuItem);
showStationBordersMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modelRoot.setProperty(ModelRoot.Property.SHOW_STATION_BORDERS,
new Boolean(showStationBordersMenuItem.isSelected()));
mapViewJComponent.refreshAll();
}
});
final JCheckBoxMenuItem playSoundsMenuItem = new JCheckBoxMenuItem(
"Play sounds", true);
displayMenu.add(playSoundsMenuItem);
playSoundsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modelRoot.setProperty(ModelRoot.Property.PLAY_SOUNDS,
new Boolean(playSoundsMenuItem.isSelected()));
}
});
;
boolean showFps = Boolean.parseBoolean(System.getProperty("SHOWFPS"));
final JCheckBoxMenuItem showFPSMenuItem = new JCheckBoxMenuItem(
"Show FPS stats", showFps);
displayMenu.add(showFPSMenuItem);
showFPSMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String newValue = String.valueOf(showFPSMenuItem.isSelected());
System.setProperty("SHOWFPS", newValue);
}
});
return displayMenu;
}
public JMenu createGameMenu() {
sc = actionRoot.getServerControls();
JMenu gameMenu = new JMenu("Game");
gameMenu.setMnemonic(71);
JMenuItem quitJMenuItem = new JMenuItem("Exit Game");
quitJMenuItem.setMnemonic(88);
quitJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
final JMenu newGameJMenu = new JMenu(sc.getNewGameAction());
newGameJMenu.addMenuListener(new MenuListener() {
public void menuCanceled(MenuEvent e) {
}
public void menuDeselected(MenuEvent e) {
}
public void menuSelected(MenuEvent e) {
newGameJMenu.removeAll();
Enumeration<Action> actions = sc.getMapNames().getActions();
while (actions.hasMoreElements()) {
JMenuItem mi = new JMenuItem(actions.nextElement());
newGameJMenu.add(mi);
}
}
});
JMenuItem saveGameJMenuItem = new JMenuItem(sc.getSaveGameAction());
JMenuItem loadGameJMenuItem = new JMenuItem(sc.getLoadGameAction());
// Fix bug 1102806 Newspaper does nothing, so hide it.
// JMenuItem newspaperJMenuItem = new JMenuItem("Newspaper");
// newspaperJMenuItem.setMnemonic(78);
// newspaperJMenuItem.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// dialogueBoxController.showNewspaper("Headline");
// //glassPanel.setVisible(true);
// }
// });
// Set up the game speed sub-menu.
JMenu gameSpeedSubMenu = new JMenu("Game Speed");
ButtonGroup group = new ButtonGroup();
speedActions = sc.getSetTargetTickPerSecondActions();
Enumeration<MappedButtonModel> buttonModels = speedActions
.getButtonModels();
Enumeration<Action> actions = speedActions.getActions();
while (buttonModels.hasMoreElements()) {
JRadioButtonMenuItem mi = new JRadioButtonMenuItem(actions
.nextElement());
mi.setModel(buttonModels.nextElement());
group.add(mi);
gameSpeedSubMenu.add(mi);
}
gameMenu.add(newGameJMenu);
gameMenu.addSeparator();
gameMenu.add(loadGameJMenuItem);
gameMenu.add(saveGameJMenuItem);
gameMenu.addSeparator();
gameMenu.add(gameSpeedSubMenu);
// gameMenu.add(newspaperJMenuItem);
gameMenu.addSeparator();
gameMenu.add(quitJMenuItem);
if (CHEAT) {
/** For testing. */
final ActionListener build200trains = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
WorldIterator wi = new NonNullElements(KEY.STATIONS,
modelRoot.getWorld(), modelRoot.getPrincipal());
if (wi.next()) {
Random randy = new Random();
StationModel station = (StationModel) wi.getElement();
ImList<PlannedTrain> before = station
.getProduction();
int numberOfEngineTypes = modelRoot.getWorld().size(
SKEY.ENGINE_TYPES) - 1;
int numberOfcargoTypes = modelRoot.getWorld().size(
SKEY.CARGO_TYPES) - 1;
PlannedTrain[] temp = new PlannedTrain[200];
for (int i = 0; i < temp.length; i++) {
int engineType = randy.nextInt(numberOfEngineTypes);
int[] wagonTypes = new int[] {
randy.nextInt(numberOfcargoTypes),
randy.nextInt(numberOfcargoTypes),
randy.nextInt(numberOfcargoTypes) };
PlannedTrain plannedTrain = new PlannedTrain(engineType, wagonTypes);
temp[i] = plannedTrain;
}
ImList<PlannedTrain> after = new ImList<PlannedTrain>(temp);
Move m = new ChangeProductionAtEngineShopMove(before,
after, wi.getIndex(), modelRoot.getPrincipal());
modelRoot.doMove(m);
}
}
};
JMenuItem build200TrainsMenuItem = new JMenuItem(
"Build 200 trains!");
build200TrainsMenuItem.addActionListener(build200trains);
gameMenu.add(build200TrainsMenuItem);
}
return gameMenu;
}
public JMenu createHelpMenu() {
helpMenu = new javax.swing.JMenu("Help");
JMenuItem about = new JMenuItem("About");
about.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showAbout();
}
});
JMenuItem how2play = new JMenuItem("Getting started");
how2play.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showHow2Play();
}
});
JMenuItem showControls = new JMenuItem("Show game controls");
showControls.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showGameControls();
}
});
JMenuItem showJavaProperties = new JMenuItem("Show Java Properties");
showJavaProperties
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showJavaProperties();
}
});
JMenuItem showReportBug = new JMenuItem("Report Bug");
showReportBug.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showReportBug();
}
});
helpMenu.add(showControls);
helpMenu.add(how2play);
helpMenu.add(showJavaProperties);
helpMenu.add(showReportBug);
helpMenu.add(about);
return helpMenu;
}
public JScrollPane createMainMap() {
return mainMapScrollPane1;
}
public JPanel createOverviewMap() {
return overviewMapContainer;
}
public JMenu createReportsMenu() {
reportsMenu = new javax.swing.JMenu("Reports");
JMenuItem incomeStatementJMenuItem = new JMenuItem("Income Statement");
incomeStatementJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showIncomeStatement();
}
});
JMenuItem balanceSheetJMenuItem = new JMenuItem("Balance Sheet");
balanceSheetJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showBalanceSheet();
}
});
leaderBoardJMenuItem = new JMenuItem("Leaderboard");
leaderBoardJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showLeaderBoard();
}
});
networthGraphJMenuItem = new JMenuItem("Networth Graph");
networthGraphJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showNetworthGraph();
}
});
reportsMenu.add(balanceSheetJMenuItem);
reportsMenu.add(incomeStatementJMenuItem);
reportsMenu.add(leaderBoardJMenuItem);
reportsMenu.add(networthGraphJMenuItem);
return reportsMenu;
}
public JTabbedPane createTrainsJTabPane() {
return trainsJTabPane;
}
public BuildTrackController getBuildTrackController() {
return mainMap.getBuildTrackController();
}
public boolean isSetup() {
return isSetup;
}
public void itemAdded(KEY key, int index, FreerailsPrincipal principal) {
boolean rightPrincipal = principal
.equals(this.modelRoot.getPrincipal());
if (KEY.TRAINS == key && rightPrincipal) {
countTrains();
} else if (KEY.STATIONS == key && rightPrincipal) {
countStations();
}
}
public void itemRemoved(KEY key, int index, FreerailsPrincipal principal) {
// do nothing
}
public void listUpdated(KEY key, int index, FreerailsPrincipal principal) {
boolean rightPrincipal = principal
.equals(this.modelRoot.getPrincipal());
if (KEY.TRAINS == key && rightPrincipal) {
countTrains();
} else if (KEY.STATIONS == key && rightPrincipal) {
countStations();
}
}
/**
* Called when a new game is started or a game is loaded.
* <p>
* <b>Be extremely careful with the references of objects allocated in this
* method to avoid memory leaks - see bug 967677 (OutOfMemoryError after
* starting several new games). </b>
* </p>
*/
public void setup(RenderersRoot vl, ReadOnlyWorld w) throws IOException {
/*
* Set the cursor position. The initial cursor position is 0,0. However,
* if a game is loaded or a new game is started and the map size is the
* same as the last map size, then the cursor should take the position
* it had on the last map.
*/
ImPoint cursorPosition = new ImPoint(0, 0);
if (null != world) {
if (w.getMapWidth() == world.getMapWidth()
&& w.getMapHeight() == world.getMapHeight()) {
cursorPosition = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.CURSOR_POSITION);
}
}
renderers = vl;
world = w;
modelRoot.addMapListener(this);
modelRoot.addListListener(this);
if (!vl.validate(world)) {
throw new IllegalArgumentException("The specified"
+ " RenderersRoot are not compatible with the clients"
+ "world!");
}
// create the main and overview maps
mainMap = new DetailMapRenderer(world, renderers, modelRoot);
TrainRenderer trainRenderer = mainMap.getTrainRenderer();
Dimension maxSize = new Dimension(200, 200);
overviewMap = ZoomedOutMapRenderer.getInstance(world, maxSize);
stationTypesPopup.setup(modelRoot, actionRoot, mainMap
.getStationRadius());
mapViewJComponent
.setup(mainMap, modelRoot, renderers);
// setup the the main and overview map JComponents
dialogueBoxController.setDefaultFocusOwner(mapViewJComponent);
userInputOnMapController.setup(mapViewJComponent, actionRoot
.getTrackMoveProducer(), stationTypesPopup, this.modelRoot,
dialogueBoxController, mapViewJComponent.getMapCursor(),
getBuildTrackController(), trainRenderer);
buildMenu.setup(actionRoot);
mainMapScrollPane1.setViewportView(this.mapViewJComponent);
((OverviewMapJComponent) overviewMapContainer).setup(overviewMap);
datejLabel.setup(modelRoot, vl, null);
cashjLabel.setup(modelRoot, vl, null);
trainsJTabPane.setup(actionRoot, vl, modelRoot);
dialogueBoxController.setup(modelRoot, vl);
StationPlacementCursor.wireUp(actionRoot, mainMap.getStationRadius(),
mapViewJComponent);
int gameSpeed = ((GameSpeed) world.get(ITEM.GAME_SPEED)).getSpeed();
/* Set the selected game speed radio button. */
String actionName = actionRoot.getServerControls().getGameSpeedDesc(
gameSpeed);
speedActions.setSelectedItem(actionName);
userMessageGenerator.logSpeed();
/*
* Count stations and trains to determine if we need to display the
* station and train menu items and tabs.3
*/
countStations();
countTrains();
String name = modelRoot.getPrincipal().getName();
String serverDetails = (String) modelRoot
.getProperty(ModelRoot.Property.SERVER);
String frameTitle;
if (serverDetails.equals(LocalConnection.SERVER_IN_SAME_JVM)) {
frameTitle = name + " - Freerails";
} else {
frameTitle = name + " - " + serverDetails + " - Freerails";
}
clientJFrame.setTitle(frameTitle);
isSetup = true;
modelRoot.setProperty(ModelRoot.Property.CURSOR_POSITION,
cursorPosition);
mapViewJComponent.requestFocus();
}
/**
* Listens for changes on the map, for instance when track is built, and
* refreshes the map views.
*/
public void tilesChanged(Rectangle tilesChanged) {
logger.fine("TilesChanged = " + tilesChanged);
// If lots of tiles have changed, do a complete refresh.
int size = tilesChanged.width * tilesChanged.height;
if (size > 100) {
mainMap.refreshAll();
overviewMap.refreshAll();
} else {
Point tile = new Point();
// Fix for bug 967673 (Crash when building track close to edge of
// map).
Rectangle mapRect = new Rectangle(0, 0, world.getMapWidth(), world
.getMapHeight());
tilesChanged = tilesChanged.intersection(mapRect);
for (tile.x = tilesChanged.x; tile.x < (tilesChanged.x + tilesChanged.width); tile.x++) {
for (tile.y = tilesChanged.y; tile.y < (tilesChanged.y + tilesChanged.height); tile.y++) {
mainMap.refreshTile(tile.x, tile.y);
overviewMap.refreshTile(tile.x, tile.y);
}
}
}
}
}
Methods:
MethodJavadoc
countStations
countTrains
createBrokerMenu
createBuildMenu/**
createCashJLabel
createClientJFrame
createDateJLabel
createDisplayMenu
createGameMenu
createHelpMenu
createMainMap
createOverviewMap
createReportsMenu
createTrainsJTabPane
getBuildTrackController
isSetup
itemAdded/**
itemRemoved
listUpdated
setup/**
tilesChanged/**
jfreerails.client.top.GUIComponentFactoryTestImpl
Javadoc:
/** * Implementation of GUIComponentFactory that returns 'blank' components - used * for testing the layout of ClientJFrame. * * @author Luke */
Source code:
/**
* Implementation of GUIComponentFactory that returns 'blank' components - used
* for testing the layout of ClientJFrame.
*
* @author Luke
*/
public class GUIComponentFactoryTestImpl implements GUIComponentFactory {
private final JLabel datejLabel;
private final JLabel cashjLabel;
private final JTabbedPane trainsJPanel;
private final JMenu displayMenu;
private final JScrollPane mainMapView;
private final JMenu buildMenu;
private final JMenu gameMenu;
private final JPanel mapOverview;
private final JMenu helpMenu;
private final JLabel messageJLabel;
private final JMenu brokerMenu;
/** Creates a new instance of GUIComponentFactoryTestImpl. */
public GUIComponentFactoryTestImpl() {
JPanel mainmapjPanel;
trainsJPanel = new JTabbedPane();
datejLabel = new JLabel();
mapOverview = new JPanel();
cashjLabel = new JLabel();
mainMapView = new JScrollPane();
mainmapjPanel = new JPanel();
messageJLabel = new JLabel();
gameMenu = new JMenu();
buildMenu = new JMenu();
displayMenu = new JMenu();
helpMenu = new JMenu();
brokerMenu = new JMenu();
trainsJPanel.setBackground(new java.awt.Color(255, 51, 51));
datejLabel.setText("Jun, 1840");
mapOverview.setBackground(new java.awt.Color(0, 204, 255));
mapOverview.setPreferredSize(new java.awt.Dimension(100, 100));
cashjLabel.setText("$100,000");
mainmapjPanel.setBackground(new java.awt.Color(153, 244, 51));
mainMapView.setViewportView(mainmapjPanel);
messageJLabel.setText("message");
}
public JMenu createReportsMenu() {
return new JMenu("Reports");
}
public JMenu createBuildMenu() {
return buildMenu;
}
public JLabel createCashJLabel() {
return cashjLabel;
}
public JLabel createDateJLabel() {
return datejLabel;
}
public JMenu createDisplayMenu() {
return displayMenu;
}
public JMenu createGameMenu() {
return gameMenu;
}
public JMenu createHelpMenu() {
return helpMenu;
}
public JScrollPane createMainMap() {
return mainMapView;
}
public JPanel createOverviewMap() {
return mapOverview;
}
public JTabbedPane createTrainsJTabPane() {
return trainsJPanel;
}
public JMenu createBrokerMenu() {
return brokerMenu;
}
}
Methods:
MethodJavadoc
createBrokerMenu
createBuildMenu
createCashJLabel
createDateJLabel
createDisplayMenu
createGameMenu
createHelpMenu
createMainMap
createOverviewMap
createReportsMenu
createTrainsJTabPane
jfreerails.client.top.GameLoop
Javadoc:
/** * This thread updates the GUI Client window. * * @author Luke */
Source code:
/**
* This thread updates the GUI Client window.
*
* @author Luke
*/
final public class GameLoop implements Runnable {
private static final Logger logger = Logger.getLogger(GameLoop.class
.getName());
private final static boolean LIMIT_FRAME_RATE = false;
private boolean gameNotDone = false;
private final ScreenHandler screenHandler;
private final static int TARGET_FPS = 40;
private FPScounter fPScounter;
private long frameStartTime;
private final GameModel[] model;
private final Integer loopMonitor = new Integer(0);
public GameLoop(ScreenHandler s) {
screenHandler = s;
model = new GameModel[0];
}
public GameLoop(ScreenHandler s, GameModel[] gm) {
screenHandler = s;
model = gm;
if (null == model) {
throw new NullPointerException();
}
}
public void run() {
try {
SynchronizedEventQueue.use();
RepaintManagerForActiveRendering.addJFrame(screenHandler.frame);
RepaintManagerForActiveRendering.setAsCurrentManager();
if (!screenHandler.isInUse()) {
screenHandler.apply();
}
gameNotDone = true;
fPScounter = new FPScounter();
/*
* Reduce this threads priority to avoid starvation of the input
* thread on Windows.
*/
try {
Thread.currentThread().setPriority(Thread.NORM_PRIORITY - 1);
} catch (SecurityException e) {
logger.warning("Couldn't lower priority of redraw thread");
}
while (true) {
// stats.record();
frameStartTime = System.currentTimeMillis();
/*
* Flush all redraws in the underlying toolkit. This reduces X11
* lag when there isn't much happening, but is expensive under
* Windows
*/
Toolkit.getDefaultToolkit().sync();
synchronized (SynchronizedEventQueue.MUTEX) {
if (!gameNotDone) {
SynchronizedEventQueue.MUTEX.notify();
break;
}
for (int i = 0; i < model.length; i++) {
model[i].update();
}
if (!screenHandler.isMinimised()) {
if (screenHandler.isInUse()) {
boolean contentsRestored = false;
do {
Graphics g = screenHandler.getDrawGraphics();
try {
screenHandler.frame.paintComponents(g);
boolean showFps = Boolean
.parseBoolean(System
.getProperty("SHOWFPS"));
if (showFps) {
fPScounter.drawFPS((Graphics2D) g);
}
} catch (RuntimeException re) {
/*
* We are not expecting a RuntimeException
* here. If something goes wrong, lets kill
* the game straight away to avoid
* hard-to-track-down bugs.
*/
ReportBugTextGenerator
.unexpectedException(re);
} finally {
g.dispose();
}
contentsRestored = screenHandler
.contentsRestored();
} while (contentsRestored);
screenHandler.swapScreens();
fPScounter.updateFPSCounter();
}
}
}
if (screenHandler.isMinimised()) {
try {
// The window is minimised so we don't need to keep
// updating.
Thread.sleep(200);
} catch (Exception e) {
// do nothing.
}
} else if (LIMIT_FRAME_RATE) {
long deltatime = System.currentTimeMillis()
- frameStartTime;
while (deltatime < (1000 / TARGET_FPS)) {
try {
long sleeptime = (1000 / TARGET_FPS) - deltatime;
Thread.sleep(sleeptime);
} catch (Exception e) {
e.printStackTrace();
}
deltatime = System.currentTimeMillis() - frameStartTime;
}
}
// remove all events from a event queue (max 5ms)
long startEventWaitTime = System.currentTimeMillis() + 4;
while (SynchronizedEventQueue.getInstance().peekEvent() != null) {
// we have events
Thread.yield();
if (startEventWaitTime < System.currentTimeMillis()) {
break;
}
}
}
/* signal that we are done */
synchronized (loopMonitor) {
loopMonitor.notify();
}
} catch (Exception e) {
ReportBugTextGenerator.unexpectedException(e);
}
}
}
Methods:
MethodJavadoc
run
jfreerails.client.top.QuickRGBTileRendererList
Javadoc:
/** * Simple implementation of TileRendererList, for testing purposes only. * * @author Luke * */
Source code:
/**
* Simple implementation of TileRendererList, for testing purposes only.
*
* @author Luke
*
*/
public class QuickRGBTileRendererList implements TileRendererList {
private final int[] rgbValues;
private final Image[] images;
private final HashMap<Integer, Integer> rgb2index = new HashMap<Integer, Integer>();
private final SimpleTileRenderer simpleTileRenderer = new SimpleTileRenderer();
private static final java.awt.GraphicsConfiguration defaultConfiguration = java.awt.GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
public QuickRGBTileRendererList(ReadOnlyWorld w) {
int numberOfTerrainTypes = w.size(SKEY.TERRAIN_TYPES);
rgbValues = new int[numberOfTerrainTypes];
images = new Image[numberOfTerrainTypes];
for (int i = 0; i < numberOfTerrainTypes; i++) {
TerrainType t = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
rgbValues[i] = t.getRGB();
images[i] = createImageFor(t);
rgb2index.put(new Integer(t.getRGB()), new Integer(i));
}
}
public static Image createImageFor(TerrainType t) {
Image image = defaultConfiguration.createCompatibleImage(
Constants.TILE_SIZE, Constants.TILE_SIZE);
Color c = new Color(t.getRGB());
Graphics g = image.getGraphics();
g.setColor(c);
g.fillRect(0, 0, Constants.TILE_SIZE, Constants.TILE_SIZE);
g.dispose();
return image;
}
public TileRenderer getTileViewWithNumber(int i) {
throw new UnsupportedOperationException();
}
public TileRenderer getTileViewWithRGBValue(int rgb) {
Integer i = rgb2index.get(new Integer(rgb));
this.simpleTileRenderer.setImage(images[i.intValue()]);
return simpleTileRenderer;
}
public boolean validate(ReadOnlyWorld world) {
return true;
}
class SimpleTileRenderer implements TileRenderer {
Image i;
public SimpleTileRenderer() {
}
public void setImage(Image i) {
this.i = i;
}
public Image getDefaultIcon() {
return i;
}
public void renderTile(Graphics g, int renderX, int renderY, int mapX,
int mapY, ReadOnlyWorld w) {
g.drawImage(i, renderX, renderY, null);
}
public void dumpImages(ImageManager imageManager) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
}
}
Methods:
MethodJavadoc
createImageFor
getTileViewWithNumber
getTileViewWithRGBValue
validate
jfreerails.client.top.RenderersRootImpl
Javadoc:
/** * Implementation of RenderersRoot whose constructor loads graphics and provides * feed back using a FreerailsProgressMonitor. * * @author Luke */
Source code:
/**
* Implementation of RenderersRoot whose constructor loads graphics and provides
* feed back using a FreerailsProgressMonitor.
*
* @author Luke
*/
public class RenderersRootImpl implements RenderersRoot {
private static final Logger logger = Logger.getLogger(RenderersRootImpl.class
.getName());
private final TileRendererList tiles;
private final TrackPieceRendererList trackPieceViewList;
private final ImageManager imageManager;
private final ArrayList<TrainImages> wagonImages = new ArrayList<TrainImages>();
private final ArrayList<TrainImages> engineImages = new ArrayList<TrainImages>();
public RenderersRootImpl(ReadOnlyWorld w, FreerailsProgressMonitor pm)
throws IOException {
URL out = RenderersRootImpl.class.getResource("/experimental");
imageManager = new ImageManagerImpl("/jfreerails/client/graphics/", out
.getPath());
tiles = loadNewTileViewList(w, pm);
trackPieceViewList = loadTrackViews(w, pm);
//rr = new OldTrainImages(w, imageManager, pm);
loadTrainImages(w, pm);
preloadSounds(pm);
}
private void loadTrainImages(ReadOnlyWorld w, FreerailsProgressMonitor pm)
throws IOException {
// Setup progress monitor..
final int numberOfWagonTypes = w.size(SKEY.CARGO_TYPES);
final int numberOfEngineTypes = w.size(SKEY.ENGINE_TYPES);
pm.nextStep(numberOfWagonTypes + numberOfEngineTypes);
int progress = 0;
pm.setValue(progress);
//Load wagon images.
for (int i = 0; i < numberOfWagonTypes; i++) {
CargoType cargoType = (CargoType) w.get(SKEY.CARGO_TYPES, i);
String name = cargoType.getName();
TrainImages ti = new TrainImages(imageManager, name);
wagonImages.add(ti);
pm.setValue(++progress);
}
//Load engine images
for (int i = 0; i < numberOfEngineTypes; i++) {
EngineType engineType = (EngineType) w.get(SKEY.ENGINE_TYPES, i);
String engineTypeName = engineType
.getEngineTypeName();
TrainImages ti = new TrainImages(imageManager, engineTypeName);
engineImages.add(ti);
pm.setValue(++progress);
}
}
private void preloadSounds(FreerailsProgressMonitor pm) {
// Pre-load sounds..
String[] soundsFiles = { "/jfreerails/client/sounds/buildtrack.wav",
"/jfreerails/client/sounds/cash.wav",
"/jfreerails/client/sounds/removetrack.wav",
"/jfreerails/client/sounds/whistle.wav" };
pm.nextStep(soundsFiles.length);
SoundManager sm = SoundManager.getSoundManager();
for (int i = 0; i < soundsFiles.length; i++) {
try {
sm.addClip(soundsFiles[i]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pm.setValue(i + 1);
}
}
private TrackPieceRendererList loadTrackViews(ReadOnlyWorld w,
FreerailsProgressMonitor pm) throws IOException {
return new TrackPieceRendererList(w, imageManager, pm);
}
private TileRendererList loadNewTileViewList(ReadOnlyWorld w,
FreerailsProgressMonitor pm) throws IOException {
ArrayList<TileRenderer> tileRenderers = new ArrayList<TileRenderer>();
// Setup progress monitor..
int numberOfTypes = w.size(SKEY.TERRAIN_TYPES);
pm.nextStep(numberOfTypes);
int progress = 0;
pm.setValue(progress);
for (int i = 0; i < numberOfTypes; i++) {
TerrainType t = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
int[] typesTreatedAsTheSame = new int[] { i };
TileRenderer tr = null;
pm.setValue(++progress);
try {
// XXX hack to make rivers flow into ocean and habours & occean
// treat habours as the same type.
TerrainType.Category thisTerrainCategory = t.getCategory();
if (thisTerrainCategory.equals(TerrainType.Category.River)
|| thisTerrainCategory
.equals(TerrainType.Category.Ocean)) {
// Count number of types with category "water"
int count = 0;
for (int j = 0; j < numberOfTypes; j++) {
TerrainType t2 = (TerrainType) w.get(
SKEY.TERRAIN_TYPES, j);
TerrainType.Category terrainCategory = t2.getCategory();
if (terrainCategory.equals(TerrainType.Category.Ocean)
|| terrainCategory.equals(thisTerrainCategory)) {
count++;
}
}
typesTreatedAsTheSame = new int[count];
count = 0;
for (int j = 0; j < numberOfTypes; j++) {
TerrainType t2 = (TerrainType) w.get(
SKEY.TERRAIN_TYPES, j);
TerrainType.Category terrainCategory = t2.getCategory();
if (terrainCategory.equals(TerrainType.Category.Ocean)
|| terrainCategory.equals(thisTerrainCategory)) {
typesTreatedAsTheSame[count] = j;
count++;
}
}
}
tr = new RiverStyleTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io) {
}
try {
tr = new ForestStyleTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io) {
}
try {
tr = new ChequeredTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io) {
}
try {
tr = new StandardTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io) {
// If the image is missing, we generate it.
logger
.warning("No tile renderer for "
+ t.getTerrainTypeName());
String filename = StandardTileRenderer.generateFilename(t
.getTerrainTypeName());
Image image = QuickRGBTileRendererList.createImageFor(t);
imageManager.setImage(filename, image);
// generatedImages.setImage(filename, image);
try {
tr = new StandardTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io2) {
io2.printStackTrace();
throw new IllegalStateException();
}
}
}
// XXXX add special tile renderer for habours
TileRenderer oceanTileRenderer = null;
for (int j = 0; j < numberOfTypes; j++) {
TerrainType t2 = (TerrainType) w.get(SKEY.TERRAIN_TYPES, j);
String terrainName = t2.getTerrainTypeName();
if (terrainName.equalsIgnoreCase("Ocean")) {
oceanTileRenderer = tileRenderers.get(j);
break;
}
}
for (int j = 0; j < numberOfTypes; j++) {
TerrainType t2 = (TerrainType) w.get(SKEY.TERRAIN_TYPES, j);
String terrainName = t2.getTerrainTypeName();
if (terrainName.equalsIgnoreCase("Harbour")) {
TerrainType t = (TerrainType) w.get(SKEY.TERRAIN_TYPES, j);
TileRenderer tr = new SpecialTileRenderer(imageManager,
new int[] { j }, t, oceanTileRenderer);
tileRenderers.set(j, tr);
break;
}
}
return new TileRendererListImpl(tileRenderers);
}
public TileRendererList getTileViewList() {
return this.tiles;
}
public TrackPieceRendererList getTrackPieceViewList() {
return this.trackPieceViewList;
}
public boolean validate(ReadOnlyWorld w) {
boolean okSoFar = true;
if (!this.tiles.validate(w)) {
okSoFar = false;
}
if (!this.trackPieceViewList.validate(w)) {
okSoFar = false;
}
return okSoFar;
}
// public OldTrainImages getTrainImages() {
// return rr;
// }
public ImageManager getImageManager() {
return imageManager;
}
public Image getImage(String relativeFilename) throws IOException {
return imageManager.getImage(relativeFilename);
}
public TileRenderer getTileViewWithNumber(int i) {
return tiles.getTileViewWithNumber(i);
}
public TrackPieceRenderer getTrackPieceView(int i) {
return trackPieceViewList.getTrackPieceView(i);
}
public TrainImages getWagonImages(int type) {
return wagonImages.get(type);
}
public TrainImages getEngineImages(int type) {
return engineImages.get(type);
}
public Image getScaledImage(String relativeFilename, int height) throws IOException {
return imageManager.getScaledImage(relativeFilename, height);
}
}
Methods:
MethodJavadoc
getEngineImages
getImage
getImageManager
getScaledImage
getTileViewList
getTileViewWithNumber
getTrackPieceView
getTrackPieceViewList
getWagonImages
loadNewTileViewList
loadTrackViews
loadTrainImages
preloadSounds
validate
jfreerails.client.top.StationTypesPopup
Javadoc:
/** * This JPopupMenu displays the list of station types that are available and * builds the type that is selected. * * @author Luke Lindsay 08-Nov-2002 * */
Source code:
/**
* This JPopupMenu displays the list of station types that are available and
* builds the type that is selected.
*
* @author Luke Lindsay 08-Nov-2002
*
*/
public class StationTypesPopup extends JPopupMenu {
private static final long serialVersionUID = 3258415040658093364L;
private Point tileToBuildStationOn;
private StationRadiusRenderer stationRadiusRenderer;
private PopupMenuListener popupMenuListener;
private StationBuildModel stationBuildModel;
private ModelRoot modelRoot;
public StationTypesPopup() {
}
public boolean canBuiltStationHere(Point p) {
stationBuildModel.getStationBuildAction().putValue(
StationBuildModel.StationBuildAction.STATION_POSITION_KEY, p);
FreerailsTile tile = (FreerailsTile) modelRoot.getWorld().getTile(p.x,
p.y);
return tile.hasTrack();
}
private class StationBuildMenuItem extends JMenuItem {
private static final long serialVersionUID = 3256721792751120946L;
@Override
public void configurePropertiesFromAction(Action a) {
super.configurePropertiesFromAction(a);
}
}
public void setup(ModelRoot mr, ActionRoot actionRoot,
StationRadiusRenderer srr) {
modelRoot = mr;
stationBuildModel = actionRoot.getStationBuildModel();
stationRadiusRenderer = srr;
this.removeAll();
this.removePopupMenuListener(popupMenuListener);
popupMenuListener = new PopupMenuListener() {
public void popupMenuCanceled(PopupMenuEvent e) {
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
stationRadiusRenderer.hide();
stationBuildModel.getStationCancelAction().actionPerformed(
new ActionEvent(StationTypesPopup.this,
ActionEvent.ACTION_PERFORMED, ""));
}
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
stationRadiusRenderer.setPosition(tileToBuildStationOn.x,
tileToBuildStationOn.y);
stationBuildModel
.getStationBuildAction()
.putValue(
StationBuildModel.StationBuildAction.STATION_POSITION_KEY,
tileToBuildStationOn);
}
};
this.addPopupMenuListener(popupMenuListener);
final Action[] stationChooseActions = stationBuildModel
.getStationChooseActions();
for (int i = 0; i < stationChooseActions.length; i++) {
final StationBuildMenuItem rbMenuItem = new StationBuildMenuItem();
final int index = i;
rbMenuItem.configurePropertiesFromAction(stationChooseActions[i]);
rbMenuItem.setIcon(null);
// Show the relevant station radius when the station type's
// menu item gets focus.
rbMenuItem.addChangeListener(new ChangeListener() {
private boolean armed = false;
public void stateChanged(ChangeEvent e) {
if (rbMenuItem.isArmed() && (rbMenuItem.isArmed() != armed)) {
stationChooseActions[index]
.actionPerformed(new ActionEvent(rbMenuItem,
ActionEvent.ACTION_PERFORMED, ""));
}
armed = rbMenuItem.isArmed();
}
});
rbMenuItem.addActionListener(stationBuildModel
.getStationBuildAction());
add(rbMenuItem);
}
stationBuildModel.getStationBuildAction().addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if (e
.getPropertyName()
.equals(
StationBuildModel.StationBuildAction.STATION_RADIUS_KEY)) {
int newRadius = ((Integer) e.getNewValue())
.intValue();
stationRadiusRenderer.setRadius(newRadius);
}
if (stationBuildModel.getStationBuildAction()
.isEnabled()) {
stationRadiusRenderer.show();
} else {
stationRadiusRenderer.hide();
}
}
});
}
public void showMenu(Component invoker, int x, int y, Point tile) {
tileToBuildStationOn = tile;
super.show(invoker, x, y);
}
@Override
public void setVisible(boolean b) {
// If this popup is visible, we don't want the station's position to
// follow the mouse.
stationBuildModel.setPositionFollowsMouse(!b);
super.setVisible(b);
}
}
Methods:
MethodJavadoc
canBuiltStationHere
setVisible
setup
showMenu
jfreerails.client.top.SynchronizedEventQueue
Javadoc:
/** * This event queue is synchronized on the MUTEX. This lets one control when * events can be dispatched. * * Note, changed to be a singleton to get it working on pre 1.4.2 VMs. * * @author Luke * */
Source code:
/**
* This event queue is synchronized on the MUTEX. This lets one control when
* events can be dispatched.
*
* Note, changed to be a singleton to get it working on pre 1.4.2 VMs.
*
* @author Luke
*
*/
final public class SynchronizedEventQueue extends EventQueue {
public static final Object MUTEX = new Object();
private static final SynchronizedEventQueue instance = new SynchronizedEventQueue();
private static boolean alreadyInUse = false;
/** Enforce singleton property. */
private SynchronizedEventQueue() {
}
public static synchronized void use() {
if (!alreadyInUse) {
/* set up the synchronized event queue */
EventQueue eventQueue = Toolkit.getDefaultToolkit()
.getSystemEventQueue();
eventQueue.push(instance);
alreadyInUse = true;
}
}
@Override
protected void dispatchEvent(AWTEvent aEvent) {
synchronized (MUTEX) {
try {
super.dispatchEvent(aEvent);
} catch (Exception e) {
/*
* If something goes wrong, lets kill the game straight away to
* avoid hard-to-track-down bugs.
*/
ReportBugTextGenerator.unexpectedException(e);
}
}
}
public static SynchronizedEventQueue getInstance() {
return instance;
}
}
Methods:
MethodJavadoc
dispatchEvent
getInstance
use
jfreerails.client.top.UserInputOnMapController
Javadoc:
/** * Handles key presses and mouse movements on the map - responsible for moving * the cursor etc. * * @author Luke */
Source code:
/**
* Handles key presses and mouse movements on the map - responsible for moving
* the cursor etc.
*
* @author Luke
*/
public class UserInputOnMapController extends KeyAdapter {
private static final String JFREERAILS_CLIENT_SOUNDS_BUILDTRACK_WAV = "/jfreerails/client/sounds/buildtrack.wav";
private static final Logger logger = Logger
.getLogger(UserInputOnMapController.class.getName());
private StationTypesPopup stationTypesPopup;
private BuildIndustryJPopupMenu buildIndustryJPopupMenu = new BuildIndustryJPopupMenu();
private MapViewJComponent mapView;
private TrackMoveProducer trackBuilder;
private DialogueBoxController dialogueBoxController;
private final ModelRoot modelRoot;
private final ActionRoot actionRoot;
private final MouseInputAdapter mouseInputAdapter = new CursorMouseAdapter();
/**
* Used to determine if mouse clicks are on trains.
*/
private TrainRenderer trainRenderer;
private BuildTrackController buildTrack;
private SoundManager soundManager = SoundManager.getSoundManager();
private boolean ignoreDragging = false;
public UserInputOnMapController(ModelRoot mr, ActionRoot ar) {
modelRoot = mr;
actionRoot = ar;
}
private class CursorMouseAdapter extends MouseInputAdapter {
private boolean pressedInside = false;
@Override
public void mouseClicked(MouseEvent evt) {
boolean isDoubleClick = evt.getClickCount() == 2;
ReadOnlyWorld w = modelRoot.getWorld();
FreerailsPrincipal principal = modelRoot.getPrincipal();
if (SwingUtilities.isLeftMouseButton(evt)) {
int x = evt.getX();
int y = evt.getY();
Double time = (Double) modelRoot.getProperty(Property.TIME);
int clickedTrain = -1;
//Iterate in reverse order since later trains are rendered over earlier ones.
for (int i = w.size(principal, KEY.TRAINS) -1; i >= 0 ; i--) {
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS, i);
TrainAccessor ta = new TrainAccessor(w, principal, i);
TrainPositionOnMap pos = ta.findPosition(time);
List<Map.Entry<Point, Step>> positions = trainRenderer.calcPositions(train, pos);
boolean hit = trainRenderer.isHit(evt.getPoint(), train, positions);
if(hit){
clickedTrain = i;
break;
}
}
if (clickedTrain != -1) {
modelRoot.setProperty(Property.SELECTED_TRAIN, clickedTrain);
if (isDoubleClick) {
dialogueBoxController.showTrainOrders(clickedTrain);
}
} else {
if (isDoubleClick) {
ImPoint cursorPosition = (ImPoint) modelRoot.getProperty(Property.CURSOR_POSITION);
dialogueBoxController.showStationOrTerrainInfo(cursorPosition.x,
cursorPosition.y);
}
}
}
}
@Override
public void mousePressed(MouseEvent evt
) {
if (SwingUtilities.isLeftMouseButton(evt)) {
ignoreDragging = false;
int x = evt.getX();
int y = evt.getY();
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
// only jump - no track building
moveCursorJump(new ImPoint(x / tileSize.width, y
/ tileSize.height));
mapView.requestFocus();
pressedInside = true;
/*
* Fix for bug [ 972866 ] Build track by dragging - only when
* build track selected
*/
boolean isBuildTrackModeSet = trackBuilder
.getTrackBuilderMode() == BUILD_TRACK;
if (isBuildTrackModeSet) {
buildTrack.show();
}
} else if (SwingUtilities.isRightMouseButton(evt)) {
// Cancel building track.
buildTrack.hide();
ignoreDragging = true;
setIgnoreKeyEvents(false);
}
}
@Override
public void mouseDragged(MouseEvent evt
) {
BuildMode trackBuilderMode = trackBuilder.getTrackBuilderMode();
/*
* Fix for bug [ 972866 ] Build track by dragging - only when build
* track selected
* Fix for bug [1537413 ] Exception when building station.
*/
boolean trackBuildingOn = (trackBuilderMode == BUILD_TRACK)
|| (trackBuilderMode == REMOVE_TRACK)
|| (trackBuilderMode == UPGRADE_TRACK);
trackBuildingOn = trackBuildingOn
&& (modelRoot.getProperty(ModelRoot.Property.CURSOR_MODE) == ModelRoot.Value.BUILD_TRACK_CURSOR_MODE);
if (SwingUtilities.isLeftMouseButton(evt) && pressedInside
&& trackBuildingOn && !ignoreDragging) {
setIgnoreKeyEvents(true);
int x = evt.getX();
int y = evt.getY();
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
int tileX = x / tileSize.width;
int tileY = y / tileSize.height;
/*
* See the javadoc for JComponent.setAutoscrolls(boolean
* autoscrolls)
*/
assert mapView.getAutoscrolls();
// Scroll view if necessary.
if (!mapView.getVisibleRect().contains(x, y)) {
/*
* Making the rectangle we scroll to 2 tiles wide and
* centered on x, y means that we scroll at least one tile.
* This stops painfully slow scrolling in full screen mode
* when the mouse cannot be dragged far from the viewport
* since it hits the screen edge.
*/
Rectangle r = new Rectangle(x - tileSize.width, y
- tileSize.height, 2 * tileSize.width,
2 * tileSize.height);
mapView.scrollRectToVisible(r);
}
ImPoint to = new ImPoint(
tileX, tileY);
buildTrack.setProposedTrack(to, trackBuilder);
mapView.requestFocus();
}
}
@Override
public void mouseReleased(MouseEvent evt
) {
if (SwingUtilities.isLeftMouseButton(evt)) {
ignoreDragging = false;
setIgnoreKeyEvents(false);
// build a railroad from x,y to current cursor position
if (pressedInside && buildTrack.isBuilding()
&& buildTrack.isBuildTrackSuccessful()) {
// Fix for bug [ 997088 ]
// Is current posisition different from original position?
int x = evt.getX();
int y = evt.getY();
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
int tileX = x / tileSize.width;
int tileY = y / tileSize.height;
if (getCursorPosition().x != tileX
|| getCursorPosition().y != tileY) {
// copy WorldDifferences from buildTrack to World
ImPoint newPosition = buildTrack
.updateWorld(trackBuilder);
setCursorPosition(newPosition);
}
}
pressedInside = false;
buildTrack.hide();
}
}
}
private void cursorOneTileMove(ImPoint oldPosition, Step vector) {
boolean b = (modelRoot.getProperty(ModelRoot.Property.CURSOR_MODE) == ModelRoot.Value.BUILD_TRACK_CURSOR_MODE);
if (null != trackBuilder && b) {
trackBuilder.setBuildTrackStrategy(getBts());
MoveStatus ms = trackBuilder.buildTrack(oldPosition, vector);
if (ms.ok) {
setCursorMessage("");
playAppropriateSound();
} else {
setCursorMessage(ms.message);
}
} else {
logger.warning("No track builder available!");
}
}
private void playAppropriateSound() {
switch (trackBuilder.getTrackBuilderMode()) {
case BUILD_TRACK:
case UPGRADE_TRACK:
soundManager.playSound(JFREERAILS_CLIENT_SOUNDS_BUILDTRACK_WAV, 0);
break;
case REMOVE_TRACK:
soundManager.playSound("/jfreerails/client/sounds/removetrack.wav",
0);
break;
default:
// do nothing
}
}
public void setup(MapViewJComponent mv, TrackMoveProducer trackBuilder,
StationTypesPopup stPopup, ModelRoot mr, DialogueBoxController dbc,
FreerailsCursor cursor, BuildTrackController buildTrack, TrainRenderer trainRenderer) {
this.dialogueBoxController = dbc;
this.mapView = mv;
this.stationTypesPopup = stPopup;
this.trackBuilder = trackBuilder;
this.buildTrack = buildTrack;
this.trainRenderer = trainRenderer;
buildIndustryJPopupMenu.setup(mr, null, null);
/*
* We attempt to remove listeners before adding them to prevent them
* being added several times.
*/
mapView.removeMouseListener(mouseInputAdapter);
mapView.addMouseListener(mouseInputAdapter);
mapView.removeMouseMotionListener(mouseInputAdapter);
mapView.addMouseMotionListener(mouseInputAdapter);
mapView.removeKeyListener(this);
mapView.addKeyListener(this);
}
private void cursorJumped(ImPoint to) {
// if (trackBuilder.getTrackBuilderMode() ==
// TrackMoveProducer.UPGRADE_TRACK) {
// MoveStatus ms = trackBuilder.upgradeTrack(to);
//
// if (ms.ok) {
// setCursorMessage("");
// playAppropriateSound();
// } else {
// setCursorMessage(ms.message);
// }
// }
}
private ImPoint getCursorPosition() {
ImPoint point = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.CURSOR_POSITION);
// Check for null
point = null == point ? new ImPoint() : point;
return point;
}
private void setCursorPosition(ImPoint p) {
// Make a defensive copy.
ImPoint point = p;
modelRoot.setProperty(Property.CURSOR_POSITION, point);
}
private void setCursorMessage(String s) {
modelRoot.setProperty(Property.CURSOR_MESSAGE, s);
}
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (isIgnoreKeyEvents()) {
if (keyCode == KeyEvent.VK_ESCAPE) {
setIgnoreKeyEvents(false);
} else {
return;
}
}
ImPoint cursorPosition = getCursorPosition();
switch (keyCode) {
case KeyEvent.VK_NUMPAD1:
moveCursorOneTile(Step.SOUTH_WEST);
break;
case KeyEvent.VK_NUMPAD2:
moveCursorOneTile(Step.SOUTH);
break;
// @SonnyZ
case KeyEvent.VK_DOWN:
if (e.getModifiers() == 2) {
moveCursorOneTile(Step.SOUTH);
}
break;
// --
case KeyEvent.VK_NUMPAD3:
moveCursorOneTile(Step.SOUTH_EAST);
break;
case KeyEvent.VK_NUMPAD4:
moveCursorOneTile(Step.WEST);
break;
// @SonnyZ
case KeyEvent.VK_LEFT:
if (e.getModifiers() == 2) {
moveCursorOneTile(Step.WEST);
}
break;
// --
case KeyEvent.VK_NUMPAD6:
moveCursorOneTile(Step.EAST);
break;
// @SonnyZ
case KeyEvent.VK_RIGHT:
if (e.getModifiers() == 2) {
moveCursorOneTile(Step.EAST);
}
break;
// --
case KeyEvent.VK_NUMPAD7:
moveCursorOneTile(Step.NORTH_WEST);
break;
case KeyEvent.VK_NUMPAD8:
moveCursorOneTile(Step.NORTH);
break;
// @SonnyZ
case KeyEvent.VK_UP:
if (e.getModifiers() == 2) {
moveCursorOneTile(Step.NORTH);
}
break;
// --
case KeyEvent.VK_NUMPAD9:
moveCursorOneTile(Step.NORTH_EAST);
break;
case KeyEvent.VK_F8: {
// Check whether we can built a station here before proceeding.
if (stationTypesPopup.canBuiltStationHere(cursorPosition.toPoint())) {
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
int x = cursorPosition.x * tileSize.width;
int y = cursorPosition.y * tileSize.height;
stationTypesPopup.showMenu(mapView, x, y, cursorPosition
.toPoint());
} else {
modelRoot.setProperty(Property.QUICK_MESSAGE, "Can't"
+ " build station here!");
}
break;
}
case KeyEvent.VK_BACK_SPACE:
logger.info("Undo building track currently not implemented.");
//
// MoveStatus ms = trackBuilder.undoLastTrackMove();
//
// if (!ms.isOk()) {
// setCursorMessage(ms.message);
// }
break;
case KeyEvent.VK_I: {
dialogueBoxController.showStationOrTerrainInfo(cursorPosition.x,
cursorPosition.y);
break;
}
case KeyEvent.VK_C: {
mapView.centerOnTile(cursorPosition.toPoint());
break;
}
case KeyEvent.VK_B: {
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
int x = cursorPosition.x * tileSize.width;
int y = cursorPosition.y * tileSize.height;
buildIndustryJPopupMenu.setCursorLocation(cursorPosition.toPoint());
buildIndustryJPopupMenu.show(mapView, x, y);
break;
}
case KeyEvent.VK_ESCAPE: {
cancelProposedBuild();
break;
}
// @author SonnyZ
case KeyEvent.VK_X: {
// modelRoot.setProperty(Property.QUICK_MESSAGE, keyCode + " was
// pressed!");
dialogueBoxController.showExitDialog();
break;
}
// @SonnyZ
case KeyEvent.VK_S: {
if (e.getModifiers() == 2) {
ServerControlModel cont = actionRoot.getServerControls();
// String name = JOptionPane.showInputDialog(null, "Saved Game
// Name:","Save
// Game",JOptionPane.QUESTION_MESSAGE,null,null,modelRoot.getPrincipal().getName()).toString();
// modelRoot.setProperty(Property.QUICK_MESSAGE, name);
cont.getSaveGameAction().actionPerformed(null);
}
break;
}
// @SonnyZ
case KeyEvent.VK_L: {
if (e.getModifiers() == 2) {
ServerControlModel cont = actionRoot.getServerControls();
cont.getLoadGameAction().actionPerformed(null);
}
break;
}
// @SonnyZ
case KeyEvent.VK_M: {
// if the screen is not clicked after the broker screen is closed
// and 'M' is pressed
// again, the broker screen will never show up again.
dialogueBoxController.showBrokerScreen();
break;
}
case KeyEvent.VK_F12: {
System.out.println("Disable keyboard input!");
setIgnoreKeyEvents(true);
break;
}
}
}
private void cancelProposedBuild() {
ignoreDragging = true;
buildTrack.hide();
StationBuildModel sbm = actionRoot.getStationBuildModel();
sbm.getStationCancelAction().actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
setIgnoreKeyEvents(false);
}
private void moveCursorJump(ImPoint tryThisPoint) {
setCursorMessage("");
if (legalRectangleContains(tryThisPoint)) {
setCursorPosition(tryThisPoint);
cursorJumped(tryThisPoint);
} else {
this.setCursorMessage("Illegal cursor position!");
}
}
/**
* Checks whether specified point is in legal rectangle.
*
* @param tryThisPoint ImPoint
* @return boolean
*/
private boolean legalRectangleContains(ImPoint tryThisPoint) {
ReadOnlyWorld world = modelRoot.getWorld();
int width = world.getMapWidth();
int height = world.getMapHeight();
Rectangle legalRectangle = new Rectangle(0, 0, width, height);
return legalRectangle.contains(tryThisPoint.toPoint());
}
private void moveCursorOneTile(Step v) {
setCursorMessage(null);
ImPoint cursorMapPosition = this.getCursorPosition();
ImPoint tryThisPoint = new ImPoint(cursorMapPosition.x + v.getDx(),
cursorMapPosition.y + v.getDy());
/* Move the cursor. */
if (legalRectangleContains(tryThisPoint)) {
setCursorPosition(tryThisPoint);
cursorOneTileMove(cursorMapPosition, v);
} else {
this.setCursorMessage("Illegal cursor position!");
}
}
private BuildTrackStrategy getBts() {
BuildTrackStrategy bts = (BuildTrackStrategy) modelRoot
.getProperty(ModelRoot.Property.BUILD_TRACK_STRATEGY);
if (null == bts) {
throw new NullPointerException();
}
return bts;
}
private void setIgnoreKeyEvents(boolean ignoreKeyEvents) {
modelRoot.setProperty(Property.IGNORE_KEY_EVENTS, Boolean
.valueOf(ignoreKeyEvents));
}
private boolean isIgnoreKeyEvents() {
Boolean b = (Boolean) modelRoot.getProperty(Property.IGNORE_KEY_EVENTS);
return b.booleanValue();
}
}
Methods:
MethodJavadoc
cancelProposedBuild
cursorJumped
cursorOneTileMove
getBts
getCursorPosition/**
isIgnoreKeyEvents
keyPressed
legalRectangleContains/**
moveCursorJump
moveCursorOneTile
playAppropriateSound
setCursorMessage
setCursorPosition
setIgnoreKeyEvents
setup
jfreerails.client.top.UserMessageGenerator
Javadoc:
/** * This class inspects incoming moves and generates a user message if * appropriate. It is also used to trigger sounds. * * @author Luke * */
Source code:
/**
* This class inspects incoming moves and generates a user message if
* appropriate. It is also used to trigger sounds.
*
* @author Luke
*
*/
public class UserMessageGenerator implements MoveReceiver {
private ModelRoot modelRoot;
private ActionRoot actionRoot;
private final DecimalFormat formatter = new DecimalFormat("#,###,###");
private SoundManager soundManager = SoundManager.getSoundManager();
public UserMessageGenerator(ModelRoot mr, ActionRoot actionRoot) {
if (null == mr || null == actionRoot) {
throw new NullPointerException();
}
this.actionRoot = actionRoot;
this.modelRoot = mr;
}
public void processMove(Move move) {
if (move instanceof CompositeMove) {
ImList<Move> moves = ((CompositeMove) move).getMoves();
for (int i = 0; i < moves.size(); i++) {
processMove(moves.get(i));
}
}
if (move instanceof WorldDiffMove) {
WorldDiffMove wdm = (WorldDiffMove) move;
if (wdm.getCause().equals(WorldDiffMove.Cause.TrainArrives)) {
trainArrives(wdm);
}
} else if (move instanceof ChangeGameSpeedMove) {
logSpeed();
}
}
/** Generates a message giving details of any cargo delivered and plays
* a cash register sound to indicate that revenue is coming in.
*/
private void trainArrives(WorldDiffMove wdm) {
ArrayList<DeliverCargoReceipt> cargoDelivered = new ArrayList<DeliverCargoReceipt>();
CompositeMove listChanges = wdm.getListChanges();
for (int i = 0; i < listChanges.size(); i++) {
Move m = listChanges.getMoves().get(i);
if (m instanceof AddTransactionMove) {
AddTransactionMove atm = (AddTransactionMove) m;
if(!atm.getPrincipal().equals(modelRoot.getPrincipal())){
//We don't want to know about other players' income!
return;
}
Transaction t = atm.getTransaction();
if (t instanceof DeliverCargoReceipt) {
DeliverCargoReceipt receipt = (DeliverCargoReceipt) t;
cargoDelivered.add(receipt);
}
}
}
if (cargoDelivered.size() > 0) {
ReadOnlyWorld world = modelRoot.getWorld();
StringBuffer message = new StringBuffer();
DeliverCargoReceipt first = cargoDelivered.get(0);
int stationId = first.getStationId();
int trainId = first.getTrainId();
message.append("Train #");
message.append(trainId + 1); // So that the first train
// is #1, not #0.
message.append(" arrives at ");
StationModel station = (StationModel) world.get(modelRoot
.getPrincipal(), KEY.STATIONS, stationId);
message.append(station.getStationName());
message.append("\n");
long revenue = 0;
int[] cargoQuantities = new int[modelRoot.getWorld().size(
SKEY.CARGO_TYPES)];
for (DeliverCargoReceipt receipt : cargoDelivered) {
CargoBatch batch = receipt.getCb();
revenue += receipt.deltaCash().getAmount();
cargoQuantities[batch.getCargoType()] = receipt
.getQuantity();
}
for (int i = 0; i < cargoQuantities.length; i++) {
int j = cargoQuantities[i];
if (j > 0) {
CargoType cargoType = (CargoType) world.get(
SKEY.CARGO_TYPES, i);
message.append(j);
message.append(" ");
message.append(cargoType.getDisplayName());
message.append("\n");
}
}
message.append("Revenue $");
message.append(formatter.format(revenue));
modelRoot.setProperty(Property.QUICK_MESSAGE, message
.toString());
// Play the sound of cash coming in. The greater the
// revenue,
// the more loops of the sample we play.
int loops = (int) revenue / 4000;
try {
soundManager.playSound(
"/jfreerails/client/sounds/cash.wav", loops);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void logSpeed() {
ReadOnlyWorld world = modelRoot.getWorld();
GameSpeed speed = ((GameSpeed) world.get(ITEM.GAME_SPEED));
int gameSpeed = speed.getSpeed();
if (gameSpeed <= 0) {
modelRoot
.setProperty(Property.PERMANENT_MESSAGE, "Game is paused.");
/*
* Also hide any other message. It looks silly if it says "Game is
* paused." and "Game speed: fast" on screen at the same time!
*/
modelRoot.setProperty(Property.QUICK_MESSAGE, "");
} else {
modelRoot.setProperty(Property.PERMANENT_MESSAGE, null);
String gameSpeedDesc = actionRoot.getServerControls()
.getGameSpeedDesc(gameSpeed);
modelRoot.setProperty(Property.QUICK_MESSAGE, "Game speed: "
+ gameSpeedDesc);
}
}
}
Methods:
MethodJavadoc
logSpeed
processMove
trainArrives/** Generates a message giving details of any cargo delivered and plays
jfreerails.client.view.ActionRoot
Javadoc:
/** * Provides access to Actions change the game state and the GUI. * * @author Luke * */
Source code:
/**
* Provides access to Actions change the game state and the GUI.
*
* @author Luke
*
*/
public class ActionRoot {
private class BuildTrainDialogAction extends AbstractAction {
private static final long serialVersionUID = 3257853173002416948L;
public BuildTrainDialogAction() {
super("Build Train");
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0));
putValue(SHORT_DESCRIPTION, "Build a new train");
}
public void actionPerformed(ActionEvent e) {
if (dialogueBoxController != null) {
dialogueBoxController.showSelectEngine();
}
}
}
private final BuildTrainDialogAction buildTrainDialogAction = new BuildTrainDialogAction();
private DialogueBoxController dialogueBoxController = null;
private final ServerControlModel serverControls;
private StationBuildModel stationBuildModel;
private TrackMoveProducer trackMoveProducer;
public ActionRoot(ModelRootImpl mr) {
this.serverControls = new ServerControlModel(mr);
}
public Action getBuildTrainDialogAction() {
return buildTrainDialogAction;
}
public DialogueBoxController getDialogueBoxController() {
return dialogueBoxController;
}
public ServerControlModel getServerControls() {
return serverControls;
}
public StationBuildModel getStationBuildModel() {
return stationBuildModel;
}
public TrackMoveProducer getTrackMoveProducer() {
return trackMoveProducer;
}
public void setDialogueBoxController(
DialogueBoxController dialogueBoxController) {
this.dialogueBoxController = dialogueBoxController;
}
/**
* Call this method when a new game is started or a game is loaded.
*/
public void setup(ModelRootImpl modelRoot, RenderersRoot vl) {
serverControls.setup(modelRoot, dialogueBoxController);
if (!modelRoot.hasBeenSetup)
throw new IllegalStateException();
ReadOnlyWorld world = modelRoot.getWorld();
if (world.size(SKEY.TRACK_RULES) > 0) {
trackMoveProducer = new TrackMoveProducer(modelRoot);
stationBuildModel = new StationBuildModel(new StationBuilder(
modelRoot), vl, modelRoot);
}
}
}
Methods:
MethodJavadoc
getBuildTrainDialogAction
getDialogueBoxController
getServerControls
getStationBuildModel
getTrackMoveProducer
setDialogueBoxController
setup/**
jfreerails.client.view.ActiveView
Javadoc:
/** * Defines a standard method to initiate GUI components that need access to the * ModelRoot <b> and </b> the ActionRoot. * * @author Luke * */
Source code:
/**
* Defines a standard method to initiate GUI components that need access to the
* ModelRoot <b> and </b> the ActionRoot.
*
* @author Luke
*
*/
public interface ActiveView {
void setup(ModelRoot modelRoot, ActionRoot ar, RenderersRoot vl,
ActionListener submitButtonCallBack);
}
Methods:
MethodJavadoc
setup
jfreerails.client.view.BalanceSheetHtmlJPanel
Javadoc:
/** * A HtmlJPanel that displays the balance sheet. * * @author Luke * */
Source code:
/**
* A HtmlJPanel that displays the balance sheet.
*
* @author Luke
*
*/
public class BalanceSheetHtmlJPanel extends HtmlJPanel implements View {
private static final long serialVersionUID = 3257009873370886964L;
private String template;
private int lastNumTransactions = 0;
private ModelRoot modelRoot;
public BalanceSheetHtmlJPanel() {
super();
URL url = BalanceSheetHtmlJPanel.class
.getResource("/jfreerails/client/view/balance_sheet.htm");
template = loadText(url);
}
@Override
public void setup(ModelRoot modelRoot, RenderersRoot vl, Action closeAction) {
super.setup(modelRoot, vl, closeAction);
this.modelRoot = modelRoot;
updateHtml();
}
private void updateHtml() {
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
BalanceSheetGenerator balanceSheetGenerator = new BalanceSheetGenerator(
world, playerPrincipal);
String populatedTemplate = populateTokens(template,
balanceSheetGenerator);
setHtml(populatedTemplate);
}
@Override
protected void paintComponent(Graphics g) {
/* Check to see if the text needs updating before painting. */
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
int currentNumberOfTransactions = world
.getNumberOfTransactions(playerPrincipal);
if (currentNumberOfTransactions != lastNumTransactions) {
updateHtml();
}
super.paintComponent(g);
}
}
Methods:
MethodJavadoc
paintComponent
setup
updateHtml
jfreerails.client.view.BrokerJFrame
Javadoc:
/** * @author smackay * @author Luke */
Source code:
/**
* @author smackay
* @author Luke
*/
public class BrokerJFrame extends javax.swing.JInternalFrame {
private static final long serialVersionUID = 4121409622587815475L;
private static final Logger logger = Logger.getLogger(BrokerJFrame.class
.getName());
/** Creates new form BrokerJFrame */
BrokerJFrame() {
initComponents();
}
public BrokerJFrame(URL url) {
initComponents();
setHtml(loadText(url));
}
public BrokerJFrame(URL url, HashMap context) {
initComponents();
String template = loadText(url);
String populatedTemplate = populateTokens(template, context);
setHtml(populatedTemplate);
}
public BrokerJFrame(String html) {
initComponents();
setHtml(html);
}
public void setup(ModelRoot m, RenderersRoot vl,
Action closeAction) {
this.done.setAction(closeAction);
}
/** Load the help text from file. */
String loadText(final URL htmlUrl) {
try {
InputStream in = htmlUrl.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
new DataInputStream(in)));
String line;
String text = "";
while ((line = br.readLine()) != null) {
text = text + line;
}
return text;
} catch (Exception e) {
e.printStackTrace();
logger.warning(htmlUrl.toString());
return "Couldn't read: " + htmlUrl;
}
}
void setHtml(String s) {
htmlJLabel.setText(s);
}
public String populateTokens(String template, Object context) {
StringTokenizer tokenizer = new StringTokenizer(template, "$");
String output = "";
while (tokenizer.hasMoreTokens()) {
output += tokenizer.nextToken();
if (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
String value;
if (context instanceof HashMap) {
value = (String) ((HashMap) context).get(token);
} else {
try {
Field field = context.getClass().getField(token);
value = field.get(context).toString();
} catch (Exception e) {
e.printStackTrace();
throw new NoSuchElementException(token);
}
}
output += value;
}
}
return output;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
htmlJLabel = new javax.swing.JLabel();
done = new javax.swing.JButton();
brokerMenu = new javax.swing.JMenuBar();
bonds = new javax.swing.JMenu();
issueBond = new javax.swing.JMenuItem();
repayBond = new javax.swing.JMenuItem();
stocks = new javax.swing.JMenu();
getContentPane().setLayout(new java.awt.GridBagLayout());
jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jPanel1.setLayout(new java.awt.BorderLayout());
htmlJLabel.setFont(new java.awt.Font("Dialog", 0, 12));
htmlJLabel.setText("sdfa");
htmlJLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
htmlJLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
jPanel1.add(htmlJLabel, java.awt.BorderLayout.CENTER);
jScrollPane1.setViewportView(jPanel1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(jScrollPane1, gridBagConstraints);
done.setText("Close");
done.setVerifyInputWhenFocusTarget(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
getContentPane().add(done, gridBagConstraints);
bonds.setText("Bonds");
issueBond.setText("Issue Bond");
bonds.add(issueBond);
repayBond.setText("Repay Bond");
bonds.add(repayBond);
brokerMenu.add(bonds);
stocks.setText("Stocks");
brokerMenu.add(stocks);
setJMenuBar(brokerMenu);
pack();
}
// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JMenu bonds;
javax.swing.JMenuBar brokerMenu;
javax.swing.JButton done;
javax.swing.JLabel htmlJLabel;
javax.swing.JMenuItem issueBond;
javax.swing.JPanel jPanel1;
javax.swing.JScrollPane jScrollPane1;
javax.swing.JMenuItem repayBond;
javax.swing.JMenu stocks;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
initComponents/** This method is called from within the constructor to
loadText/** Load the help text from file. */
populateTokens
setHtml
setup
jfreerails.client.view.BrokerScreenGenerator
Javadoc:
/** * * @author smackay * @author Luke */
Source code:
/**
*
* @author smackay
* @author Luke
*/
public class BrokerScreenGenerator {
private static final DecimalFormat DC = new DecimalFormat("#,###");
private FinancialDataGatherer dataGatherer;
private GameCalendar cal;
public String playername;
public String year;
public Money cash;
public Money loansTotal;
public Money netWorth;
public Money pricePerShare;
public String publicShares;
public String treasuryStock;
public String othersRRsStockRows;
/** Creates a new instance of BrokerScreenGenerator */
public BrokerScreenGenerator(ReadOnlyWorld w, FreerailsPrincipal principal) {
dataGatherer = new FinancialDataGatherer(w, principal);
int playerId = w.getID(principal);
this.playername = w.getPlayer(playerId).getName();
this.cal = (GameCalendar) w.get(ITEM.CALENDAR);
GameTime time = w.currentTime();
final int startyear = cal.getYear(time.getTicks());
this.year = String.valueOf(startyear);
this.cash = w.getCurrentBalance(principal);
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, principal);
aggregator.setCategory(BOND);
this.loansTotal = aggregator.calculateValue();
this.publicShares = DC.format(dataGatherer.sharesHeldByPublic());
this.netWorth = dataGatherer.netWorth();
StockPrice[] stockPrices = (new StockPriceCalculator(w)).calculate();
this.pricePerShare = stockPrices[playerId].currentPrice;
this.treasuryStock = DC.format(dataGatherer.treasuryStock());
StringBuffer otherRRsStakes = new StringBuffer();
int[] stockInThisRRs = dataGatherer.getStockInThisRRs();
for (int i = 0; i < stockInThisRRs.length; i++) {
if (i != playerId && stockInThisRRs[i] > 0) {
String otherRRName = w.getPlayer(i).getName();
String otherRRStake = DC.format(stockInThisRRs[i]);
otherRRsStakes.append("<tr> ");
otherRRsStakes.append("<td> </td>");
otherRRsStakes.append("<td> </td>");
otherRRsStakes.append("<td>" + otherRRName + "</td>");
otherRRsStakes.append("<td>" + otherRRStake + "</td>");
otherRRsStakes.append("</tr>");
}
}
othersRRsStockRows = otherRRsStakes.toString();
}
}
No methods in this class.
jfreerails.client.view.BrokerScreenHtmlJFrame
Javadoc:
/** * * @author smackay * @author Luke */
Source code:
/**
*
* @author smackay
* @author Luke
*/
public class BrokerScreenHtmlJFrame extends BrokerJFrame implements View {
private static final long serialVersionUID = 3257003246252800050L;
private String template;
private int lastNumTransactions = 0;
private ModelRoot modelRoot;
public static BrokerScreenGenerator brokerScreenGenerator;
private FinancialDataGatherer financialDataGatherer;
private Action[] buyStock, sellStock;
/** Creates a new instance of BrokerScreenHtmlJPanel */
public BrokerScreenHtmlJFrame() {
super();
URL url = BrokerScreenHtmlJFrame.class
.getResource("/jfreerails/client/view/Broker_Screen.html");
template = loadText(url);
this.setSize(550, 300);
}
private final Action issueBondAction = new AbstractAction("Issue bond") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
if (financialDataGatherer.canIssueBond()) {
Move bondTransaction = new AddTransactionMove(modelRoot
.getPrincipal(),
BondTransaction.issueBond(financialDataGatherer
.nextBondInterestRate()));
modelRoot.doMove(bondTransaction);
}
}
};
private final Action repayBondAction = new AbstractAction("Repay bond") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
Move bondTransaction = new AddTransactionMove(modelRoot
.getPrincipal(), BondTransaction.repayBond(5));
modelRoot.doMove(bondTransaction);
}
};
@Override
public void setup(final ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
super.setup(modelRoot, vl, closeAction);
financialDataGatherer = new FinancialDataGatherer(modelRoot.getWorld(),
modelRoot.getPrincipal());
this.modelRoot = modelRoot;
setupStockMenu();
updateHtml();
// Sets up the BrokerScreen and Adds ActionListeners to the Menu
issueBond.setAction(issueBondAction);
repayBond.setAction(repayBondAction);
}
private void setupStockMenu(){
stocks.removeAll();
ReadOnlyWorld world = modelRoot.getWorld();
int thisPlayerId = world.getID(modelRoot.getPrincipal());
int numberOfPlayers = world.getNumberOfPlayers();
buyStock = new Action[numberOfPlayers];
sellStock = new Action[numberOfPlayers];
for(int playerId = 0 ; playerId < numberOfPlayers; playerId++){
final boolean isThisPlayer = playerId == thisPlayerId;
final int otherPlayerId = playerId;
Player otherPlayer = world.getPlayer(playerId);
String playerLabel = isThisPlayer ? "Treasury stock" : otherPlayer.getName();
String buyLabel = "Buy 10,000 shares of " + playerLabel;
String sellLabel = "Sell 10,000 shares of " + playerLabel;
buyStock[playerId] = new AbstractAction(buyLabel) {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
StockPrice stockPrice = new StockPriceCalculator(modelRoot.getWorld()).calculate()[otherPlayerId];
Money sharePrice = isThisPlayer ? stockPrice.treasuryBuyPrice : stockPrice.buyPrice;
StockTransaction t = StockTransaction
.buyOrSellStock(otherPlayerId, StockTransaction.STOCK_BUNDLE_SIZE, sharePrice);
Move move = new AddTransactionMove(modelRoot.getPrincipal(), t);
modelRoot.doMove(move);
updateHtml();
}
};
sellStock[playerId] = new AbstractAction(sellLabel) {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
StockPrice stockPrice = new StockPriceCalculator(modelRoot.getWorld()).calculate()[otherPlayerId];
Money sharePrice = isThisPlayer ? stockPrice.treasurySellPrice : stockPrice.sellPrice;
StockTransaction t = StockTransaction
.buyOrSellStock(otherPlayerId, -StockTransaction.STOCK_BUNDLE_SIZE, sharePrice);
Move move = new AddTransactionMove(modelRoot.getPrincipal(), t);
modelRoot.doMove(move);
updateHtml();
}
};
stocks.add(buyStock[playerId]);
stocks.add(sellStock[playerId]);
}
enableAndDisableActions();
}
private void enableAndDisableActions(){
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal p = modelRoot.getPrincipal();
FinancialDataGatherer thisDataGatherer = new FinancialDataGatherer(
world, p);
StockPrice[] stockPrices = new StockPriceCalculator(world).calculate();
long highestAffordablePrice = world.getCurrentBalance(p).getAmount() / StockTransaction.STOCK_BUNDLE_SIZE;
//Enable and disable stock actions.
for(int playerId = 0; playerId < world.getNumberOfPlayers(); playerId++){
Player temp = modelRoot.getWorld().getPlayer(playerId);
FreerailsPrincipal otherPrincipal = temp.getPrincipal();
FinancialDataGatherer otherDataGatherer = new FinancialDataGatherer(world, otherPrincipal);
//If this RR has stock in other RR, then enable sell stock
boolean hasStockInRR = thisDataGatherer.getStockInRRs()[playerId] > 0;
sellStock[playerId].setEnabled(hasStockInRR);
//If the public own some stock, then enable buy stock.
boolean isStockAvailable = otherDataGatherer.sharesHeldByPublic() > 0;
buyStock[playerId].setEnabled(isStockAvailable);
//Don't let player buy 100% of treasury stock.
if(otherPrincipal.equals(p)){
int treasuryStock = otherDataGatherer.treasuryStock();
int totalStock = otherDataGatherer.totalShares();
if(StockTransaction.STOCK_BUNDLE_SIZE + treasuryStock >= totalStock){
buyStock[playerId].setEnabled(false);
}
}
//Don't let the player buy stock if they cannot afford it.
if(stockPrices[playerId].currentPrice.getAmount() > highestAffordablePrice){
buyStock[playerId].setEnabled(false);
}
}
//Enable and disable bond actions.
int outstandingBonds = thisDataGatherer.getBonds();
repayBondAction.setEnabled(outstandingBonds > 0);
issueBondAction.setEnabled(outstandingBonds < 4);
}
private void updateHtml() {
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal p = modelRoot.getPrincipal();
brokerScreenGenerator = new BrokerScreenGenerator(world, p);
// this is where the Menu get Enable and Disable by if you own any stock
// or if the TotalShares are 0
StringBuffer populatedTemplate = new StringBuffer();
populatedTemplate.append("<html>");
populatedTemplate
.append(populateTokens(template, brokerScreenGenerator));
for (int i = 0; i < world.getNumberOfPlayers(); i++) {
if (!(world.getPlayer(i).getPrincipal().equals(p))) {
BrokerScreenGenerator temp = new BrokerScreenGenerator(world,
world.getPlayer(i).getPrincipal());
populatedTemplate.append(populateTokens(template, temp));
}
}
populatedTemplate.append("</html>");
String html = populatedTemplate.toString();
setHtml(html);
enableAndDisableActions();
}
@Override
protected void paintComponent(Graphics g) {
/* Check to see if the text needs updating before painting. */
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
int currentNumberOfTransactions = world
.getNumberOfTransactions(playerPrincipal);
if (currentNumberOfTransactions != lastNumTransactions) {
updateHtml();
}
super.paintComponent(g);
}
}
Methods:
MethodJavadoc
enableAndDisableActions
paintComponent
setup
setupStockMenu
updateHtml
jfreerails.client.view.BuildTrackJPanel
Javadoc:
/** * A JPanel that presents toggle buttons that let the player select the build * mode (build track, upgrade track, build station, bulldoze, and info mode) and * select the track/bridge/station type to use. * * @author Luke */
Source code:
/**
* A JPanel that presents toggle buttons that let the player select the build
* mode (build track, upgrade track, build station, bulldoze, and info mode) and
* select the track/bridge/station type to use.
*
* @author Luke
*/
public class BuildTrackJPanel extends javax.swing.JPanel implements ActiveView {
private static final long serialVersionUID = 3618701915647850036L;
private final ImageManager imageManager = new ImageManagerImpl(
"/jfreerails/client/graphics/");
private HashMap<TrackRule.TrackCategories, Integer> selectionSet;
private ModelRoot modelRoot;
private TrackMoveProducer trackMoveProducer;
private StationBuildModel stationBuildModel;
/** Creates new form BuildTrackJPanel */
public BuildTrackJPanel() {
initComponents();
}
public void setup(ModelRoot mr, ActionRoot ar, RenderersRoot vl,
ActionListener al) {
modelRoot = mr;
stationBuildModel = ar.getStationBuildModel();
trackMoveProducer = ar.getTrackMoveProducer();
if (null == trackMoveProducer)
throw new NullPointerException();
selectionSet = new HashMap<TrackRule.TrackCategories, Integer>();
trackButtonGroup = new javax.swing.ButtonGroup();
bridgeButtonGroup = new javax.swing.ButtonGroup();
stationButtonGroup = new javax.swing.ButtonGroup();
tunnelButtonGroup = new javax.swing.ButtonGroup();
// Remove any existing buttons.
bridgesJPanel.removeAll();
stationsJPanel.removeAll();
trackJPanel.removeAll();
tunnelsJPanel.removeAll();
// Add the new set of buttons.
ReadOnlyWorld world = mr.getWorld();
for (int i = 0; i < world.size(SKEY.TRACK_RULES); i++) {
JToggleButton toggleButton = new JToggleButton();
final Integer ruleID = new Integer(i);
TrackRule rule = (TrackRule) world.get(SKEY.TRACK_RULES, i);
TrackRule.TrackCategories category = rule.getCategory();
Money price = null;
switch (category) {
case track:
trackButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon(rule.getTypeName()));
toggleButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
selectionSet
.put(TrackRule.TrackCategories.track,
ruleID);
setBuildTrackStrategy();
}
});
price = rule.getPrice();
trackJPanel.add(toggleButton);
break;
case bridge:
bridgeButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon(rule.getTypeName()));
toggleButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
selectionSet.put(
TrackRule.TrackCategories.bridge,
ruleID);
setBuildTrackStrategy();
}
});
bridgesJPanel.add(toggleButton);
price = rule.getFixedCost();
break;
case tunnel:
tunnelButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon(rule.getTypeName()));
toggleButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
selectionSet.put(
TrackRule.TrackCategories.tunnel,
ruleID);
setBuildTrackStrategy();
}
});
price = rule.getPrice();
tunnelsJPanel.add(toggleButton);
break;
case station:
stationButtonGroup.add(toggleButton);
toggleButton.setAction(stationBuildModel
.getStationChooseAction(ruleID));
toggleButton.setIcon(getIcon(rule.getTypeName()));
toggleButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
selectionSet.put(
TrackRule.TrackCategories.station,
ruleID);
}
});
stationsJPanel.add(toggleButton);
price = rule.getFixedCost();
break;
}
toggleButton.setPreferredSize(new java.awt.Dimension(36, 36));
String tooltip = Utils.capitalizeEveryWord(rule.getTypeName())
+ " $" + price.toString();
toggleButton.setToolTipText(tooltip);
if (!selectionSet.containsKey(category)) {
selectionSet.put(category, new Integer(i));
toggleButton.setSelected(true);
}
}
addNoTunnelsButton();
addNoBridgesButton();
// Default to add track.
addTrackActionPerformed(null);
buildModeButtonGroup.setSelected(addTrack.getModel(), true);
setBuildTrackStrategy();
// Make the buttons non-focusable
setFocusableFalse(bridgeButtonGroup);
setFocusableFalse(trackButtonGroup);
setFocusableFalse(tunnelButtonGroup);
setFocusableFalse(stationButtonGroup);
setFocusableFalse(buildModeButtonGroup);
// Add button click
// buildTrackJPanel.addKeyListener(new KeyListener(){
// public void keyPressed(KeyEvent e){
// System.out.println(e.getKeyCode());
// viewMode.doClick();
// }
// public void keyReleased(KeyEvent e){
//
// }
// public void keyTyped(KeyEvent e){
//
// }
// });
}
/** Calls setFocusable(false) for each button in the button group. */
private void setFocusableFalse(ButtonGroup bg) {
for (Enumeration<AbstractButton> buttons = bg.getElements(); buttons
.hasMoreElements();) {
buttons.nextElement().setFocusable(false);
}
}
private void addNoTunnelsButton() {
JToggleButton toggleButton = new JToggleButton();
tunnelButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon("no_tunnels"));
toggleButton.setPreferredSize(new java.awt.Dimension(36, 36));
toggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectionSet.put(TrackRule.TrackCategories.tunnel, null);
setBuildTrackStrategy();
}
});
toggleButton.setToolTipText("Don't build tunnels");
tunnelsJPanel.add(toggleButton);
}
private void addNoBridgesButton() {
JToggleButton toggleButton = new JToggleButton();
bridgeButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon("no_bridges"));
toggleButton.setPreferredSize(new java.awt.Dimension(36, 36));
toggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectionSet.put(TrackRule.TrackCategories.bridge, null);
setBuildTrackStrategy();
}
});
toggleButton.setToolTipText("Don't build bridges");
bridgesJPanel.add(toggleButton);
}
private ImageIcon getIcon(String typeName) {
try {
String relativeFileName = "icons" + File.separator + typeName
+ ".png";
relativeFileName = relativeFileName.replace(' ', '_');
Image im = imageManager.getImage(relativeFileName);
return new ImageIcon(im);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException(e);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
buildModeButtonGroup = new javax.swing.ButtonGroup();
trackButtonGroup = new javax.swing.ButtonGroup();
bridgeButtonGroup = new javax.swing.ButtonGroup();
stationButtonGroup = new javax.swing.ButtonGroup();
tunnelButtonGroup = new javax.swing.ButtonGroup();
buildModeJPanel = new javax.swing.JPanel();
addTrack = new javax.swing.JToggleButton();
upgradeTrack = new javax.swing.JToggleButton();
addStation = new javax.swing.JToggleButton();
bulldoze = new javax.swing.JToggleButton();
viewMode = new javax.swing.JToggleButton();
trackJPanel = new javax.swing.JPanel();
viewMode1 = new javax.swing.JToggleButton();
bridgesJPanel = new javax.swing.JPanel();
viewMode2 = new javax.swing.JToggleButton();
tunnelsJPanel = new javax.swing.JPanel();
viewMode3 = new javax.swing.JToggleButton();
stationsJPanel = new javax.swing.JPanel();
viewMode4 = new javax.swing.JToggleButton();
spacer = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
setFocusable(false);
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
@Override
public void keyTyped(java.awt.event.KeyEvent evt) {
formKeyTyped(evt);
}
});
buildModeJPanel.setLayout(new java.awt.FlowLayout(
java.awt.FlowLayout.LEFT, 4, 2));
buildModeButtonGroup.add(addTrack);
addTrack.setIcon(getIcon("build track"));
addTrack.setSelected(true);
addTrack.setToolTipText("Build Track");
addTrack.setFocusable(false);
addTrack.setPreferredSize(new java.awt.Dimension(36, 36));
addTrack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addTrackActionPerformed(evt);
}
});
buildModeJPanel.add(addTrack);
buildModeButtonGroup.add(upgradeTrack);
upgradeTrack.setIcon(getIcon("upgrade track"));
upgradeTrack.setToolTipText("Upgrade Track");
upgradeTrack.setFocusable(false);
upgradeTrack.setPreferredSize(new java.awt.Dimension(36, 36));
upgradeTrack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
upgradeTrackActionPerformed(evt);
}
});
buildModeJPanel.add(upgradeTrack);
buildModeButtonGroup.add(addStation);
addStation.setIcon(getIcon("build stations"));
addStation.setToolTipText("Build Station");
addStation.setFocusable(false);
addStation.setPreferredSize(new java.awt.Dimension(36, 36));
addStation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addStationActionPerformed(evt);
}
});
buildModeJPanel.add(addStation);
buildModeButtonGroup.add(bulldoze);
bulldoze.setIcon(getIcon("bulldozer"));
bulldoze.setToolTipText("Remove Track");
bulldoze.setFocusable(false);
bulldoze.setPreferredSize(new java.awt.Dimension(36, 36));
bulldoze.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bulldozeActionPerformed(evt);
}
});
buildModeJPanel.add(bulldoze);
buildModeButtonGroup.add(viewMode);
viewMode.setIcon(getIcon("eye"));
viewMode.setToolTipText("Don't build anything");
viewMode.setFocusable(false);
viewMode.setPreferredSize(new java.awt.Dimension(36, 36));
viewMode.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewModeActionPerformed(evt);
}
});
buildModeJPanel.add(viewMode);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(buildModeJPanel, gridBagConstraints);
trackJPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT,
4, 2));
buildModeButtonGroup.add(viewMode1);
viewMode1.setIcon(getIcon("turn_off"));
viewMode1.setPreferredSize(new java.awt.Dimension(36, 36));
trackJPanel.add(viewMode1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(trackJPanel, gridBagConstraints);
bridgesJPanel.setLayout(new java.awt.FlowLayout(
java.awt.FlowLayout.LEFT, 4, 2));
buildModeButtonGroup.add(viewMode2);
viewMode2.setIcon(getIcon("turn_off"));
viewMode2.setPreferredSize(new java.awt.Dimension(36, 36));
bridgesJPanel.add(viewMode2);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(bridgesJPanel, gridBagConstraints);
tunnelsJPanel.setLayout(new java.awt.FlowLayout(
java.awt.FlowLayout.LEFT, 4, 2));
buildModeButtonGroup.add(viewMode3);
viewMode3.setIcon(getIcon("turn_off"));
viewMode3.setPreferredSize(new java.awt.Dimension(36, 36));
tunnelsJPanel.add(viewMode3);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(tunnelsJPanel, gridBagConstraints);
stationsJPanel.setLayout(new java.awt.FlowLayout(
java.awt.FlowLayout.LEFT, 4, 2));
buildModeButtonGroup.add(viewMode4);
viewMode4.setIcon(getIcon("turn_off"));
viewMode4.setPreferredSize(new java.awt.Dimension(36, 36));
stationsJPanel.add(viewMode4);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(stationsJPanel, gridBagConstraints);
spacer.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 0,
0));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(spacer, gridBagConstraints);
}// GEN-END:initComponents
private void formKeyTyped(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_formKeyTyped
viewMode.doClick();
}// GEN-LAST:event_formKeyTyped
private void formKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_formKeyPressed
viewMode.doClick();
}// GEN-LAST:event_formKeyPressed
private void viewModeActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_viewModeActionPerformed
setVisible(false, false, false, false);
cancelStationPlacement();
setTrackBuilderMode(IGNORE_TRACK);
}// GEN-LAST:event_viewModeActionPerformed
private void bulldozeActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bulldozeActionPerformed
setVisible(false, false, false, false);
cancelStationPlacement();
setTrackBuilderMode(REMOVE_TRACK);
}// GEN-LAST:event_bulldozeActionPerformed
private void addStationActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addStationActionPerformed
setVisible(false, false, false, true);
setTrackBuilderMode(BUILD_STATION);
}// GEN-LAST:event_addStationActionPerformed
private void upgradeTrackActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_upgradeTrackActionPerformed
setVisible(true, true, false, false);
cancelStationPlacement();
setTrackBuilderMode(UPGRADE_TRACK);
}// GEN-LAST:event_upgradeTrackActionPerformed
private void addTrackActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addTrackActionPerformed
setVisible(true, true, true, false);
cancelStationPlacement();
setTrackBuilderMode(BUILD_TRACK);
}// GEN-LAST:event_addTrackActionPerformed
private void setVisible(boolean track, boolean bridges, boolean tunnels,
boolean stations) {
trackJPanel.setVisible(bridges);
bridgesJPanel.setVisible(bridges);
tunnelsJPanel.setVisible(tunnels);
stationsJPanel.setVisible(stations);
}
private void setBuildTrackStrategy() {
ArrayList<Integer> ruleIDs = new ArrayList<Integer>();
ruleIDs.add(selectionSet.get(TrackRule.TrackCategories.track));
ruleIDs.add(selectionSet.get(TrackRule.TrackCategories.bridge));
ruleIDs.add(selectionSet.get(TrackRule.TrackCategories.tunnel));
BuildTrackStrategy bts = BuildTrackStrategy.getMultipleRuleInstance(
ruleIDs, modelRoot.getWorld());
modelRoot.setProperty(ModelRoot.Property.BUILD_TRACK_STRATEGY, bts);
}
private void cancelStationPlacement() {
// Cancel build station mode..
stationBuildModel.getStationCancelAction().actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
}
private void setTrackBuilderMode(TrackMoveProducer.BuildMode mode) {
trackMoveProducer.setTrackBuilderMode(mode);
modelRoot.setProperty(ModelRoot.Property.TRACK_BUILDER_MODE, mode);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JToggleButton addStation;
private javax.swing.JToggleButton addTrack;
private javax.swing.ButtonGroup bridgeButtonGroup;
private javax.swing.JPanel bridgesJPanel;
private javax.swing.ButtonGroup buildModeButtonGroup;
private javax.swing.JPanel buildModeJPanel;
private javax.swing.JToggleButton bulldoze;
private javax.swing.JPanel spacer;
private javax.swing.ButtonGroup stationButtonGroup;
private javax.swing.JPanel stationsJPanel;
private javax.swing.ButtonGroup trackButtonGroup;
private javax.swing.JPanel trackJPanel;
private javax.swing.ButtonGroup tunnelButtonGroup;
private javax.swing.JPanel tunnelsJPanel;
private javax.swing.JToggleButton upgradeTrack;
private javax.swing.JToggleButton viewMode;
private javax.swing.JToggleButton viewMode1;
private javax.swing.JToggleButton viewMode2;
private javax.swing.JToggleButton viewMode3;
private javax.swing.JToggleButton viewMode4;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
addNoBridgesButton
addNoTunnelsButton
addStationActionPerformed
addTrackActionPerformed/**
bulldozeActionPerformed
cancelStationPlacement
formKeyPressed
formKeyTyped/**
getIcon
initComponents/**
setBuildTrackStrategy
setFocusableFalse/** Calls setFocusable(false) for each button in the button group. */
setTrackBuilderMode
setVisible
setup
upgradeTrackActionPerformed
viewModeActionPerformed
jfreerails.client.view.CargoWaitingAndDemandedJPanel
Javadoc:
/** * A JPanel that displays the cargo waiting and demanded at a station - used on * the select station popup window. * * @author Luke */
Source code:
/**
* A JPanel that displays the cargo waiting and demanded at a station - used on
* the select station popup window.
*
* @author Luke
*/
public class CargoWaitingAndDemandedJPanel extends javax.swing.JPanel implements
View {
private static final long serialVersionUID = 3760559784860071476L;
private ReadOnlyWorld world;
private FreerailsPrincipal principal;
public CargoWaitingAndDemandedJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
stationName = new javax.swing.JLabel();
waiting = new javax.swing.JLabel();
waitingJTable = new javax.swing.JTable();
demands = new javax.swing.JLabel();
demandsJList = new javax.swing.JList();
spacer = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(100, 200));
jScrollPane1.setBorder(null);
jScrollPane1
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jPanel1.setLayout(new java.awt.GridBagLayout());
stationName.setText("Station Name");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
jPanel1.add(stationName, gridBagConstraints);
waiting.setText("Waiting");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
jPanel1.add(waiting, gridBagConstraints);
waitingJTable.setBackground(javax.swing.UIManager.getDefaults()
.getColor("Button.background"));
waitingJTable.setFont(new java.awt.Font("Dialog", 0, 10));
waitingJTable.setModel(new javax.swing.table.DefaultTableModel(
new Object[][] { { "Mail", "4" }, { "Passengers", null } },
new String[] { "Title 1", "Title 2" }));
waitingJTable
.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
waitingJTable.setFocusable(false);
waitingJTable.setRequestFocusEnabled(false);
waitingJTable.setRowSelectionAllowed(false);
waitingJTable.setShowHorizontalLines(false);
waitingJTable.setShowVerticalLines(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
jPanel1.add(waitingJTable, gridBagConstraints);
demands.setText("Demands");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel1.add(demands, gridBagConstraints);
demandsJList.setBackground(javax.swing.UIManager.getDefaults()
.getColor("Button.background"));
demandsJList.setFont(new java.awt.Font("Dialog", 0, 10));
demandsJList.setFocusable(false);
demandsJList.setRequestFocusEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
jPanel1.add(demandsJList, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel1.add(spacer, gridBagConstraints);
jScrollPane1.setViewportView(jPanel1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}// GEN-END:initComponents
public void setup(ModelRoot model, RenderersRoot vl,
Action closeAction) {
this.world = model.getWorld();
this.principal = model.getPrincipal();
}
public void display(int newStationID) {
StationModel station = (StationModel) world.get(principal,
KEY.STATIONS, newStationID);
this.stationName.setText(station.getStationName());
final ImmutableCargoBundle cargoWaiting = (ImmutableCargoBundle) world
.get(principal, KEY.CARGO_BUNDLES, station.getCargoBundleID());
// count the number of cargo types waiting and demanded.
final ArrayList<String> typeWaiting = new ArrayList<String>();
final ArrayList<Integer> quantityWaiting = new ArrayList<Integer>();
final Vector<String> typeDemanded = new Vector<String>();
for (int i = 0; i < world.size(SKEY.CARGO_TYPES); i++) {
CargoType cargoType = (CargoType) world.get(SKEY.CARGO_TYPES, i);
int amountWaiting = cargoWaiting.getAmount(i);
if (0 != amountWaiting) {
typeWaiting.add(cargoType.getDisplayName());
int carloads = amountWaiting
/ WagonType.UNITS_OF_CARGO_PER_WAGON;
quantityWaiting.add(new Integer(carloads));
}
if (station.getDemand().isCargoDemanded(i)) {
typeDemanded.add(cargoType.getDisplayName());
}
}
/*
* The table shows the cargo waiting at the station. First column is
* cargo type; second column is quantity in carloads.
*/
TableModel tableModel = new AbstractTableModel() {
private static final long serialVersionUID = 3760559784860071476L;
public int getRowCount() {
return typeWaiting.size();
}
public int getColumnCount() {
return 2;
}
public Object getValueAt(int row, int column) {
if (0 == column) {
return typeWaiting.get(row);
}
return quantityWaiting.get(row);
}
};
this.waitingJTable.setModel(tableModel);
/* The list shows the cargo demanded by the station. */
this.demandsJList.setListData(typeDemanded);
this.invalidate();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel demands;
private javax.swing.JList demandsJList;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JPanel spacer;
private javax.swing.JLabel stationName;
private javax.swing.JLabel waiting;
private javax.swing.JTable waitingJTable;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
display
initComponents/**
setup
jfreerails.client.view.CashJLabel
Javadoc:
/** * This JLabel shows the amount of cash available. * * @author Luke * */
Source code:
/**
* This JLabel shows the amount of cash available.
*
* @author Luke
*
*/
public class CashJLabel extends JLabel implements View {
private static final long serialVersionUID = 3257853181542412341L;
private ReadOnlyWorld w;
private FreerailsPrincipal principal;
public CashJLabel() {
this.setText(" ");
}
public void setup(ModelRoot model, RenderersRoot vl,
Action closeAction) {
this.w = model.getWorld();
principal = model.getPrincipal();
}
@Override
protected void paintComponent(Graphics g) {
if (null != w) {
Money m = w.getCurrentBalance(principal);
String s = m.toString();
this.setText("$" + s);
}
super.paintComponent(g);
}
}
Methods:
MethodJavadoc
paintComponent
setup
jfreerails.client.view.ConfirmExitJPanel
Javadoc:
/** * JPanel that displays confirmation of exiting, used when the exit menu item is * selected or x is pressed. * * @author SonnyZ */
Source code:
/**
* JPanel that displays confirmation of exiting, used when the exit menu item is
* selected or x is pressed.
*
* @author SonnyZ
*/
public class ConfirmExitJPanel extends javax.swing.JPanel implements View {
private static final long serialVersionUID = 3256728398394110517L;
/** Creates new form ConfirmExitJPanel. */
public ConfirmExitJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
confirmExit = new javax.swing.JButton();
closeJButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(240, 140));
jLabel1.setText("Are you sure you want to Exit?");
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
jPanel1.add(jLabel1);
add(jPanel1, new java.awt.GridBagConstraints());
jPanel2.setLayout(new java.awt.GridBagLayout());
confirmExit.setText("Exit");
confirmExit.setContentAreaFilled(false);
confirmExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
confirmExitActionPerformed(evt);
}
});
jPanel2.add(confirmExit, new java.awt.GridBagConstraints());
closeJButton.setText("Cancel");
jPanel2.add(closeJButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.ipadx = 15;
gridBagConstraints.insets = new java.awt.Insets(3, 0, 0, 0);
add(jPanel2, gridBagConstraints);
}// GEN-END:initComponents
private void confirmExitActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_confirmExitActionPerformed
System.exit(0);
}// GEN-LAST:event_confirmExitActionPerformed
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
closeJButton.setAction(closeAction);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton closeJButton;
private javax.swing.JButton confirmExit;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
confirmExitActionPerformed
initComponents/**
setup
jfreerails.client.view.DateJLabel
Javadoc:
/** * This JLabel shows the current date. * * @author Luke * */
Source code:
/**
* This JLabel shows the current date.
*
* @author Luke
*
*/
public class DateJLabel extends JLabel implements View {
private static final long serialVersionUID = 3689348840578757942L;
private ReadOnlyWorld w;
public DateJLabel() {
this.setText(" ");
}
@Override
protected void paintComponent(Graphics g) {
if (null != w) {
GameTime time = w.currentTime();
GameCalendar gameCalendar = (GameCalendar) w.get(ITEM.CALENDAR);
String s = gameCalendar.getYearAndMonth(time.getTicks());
super.setText(s);
}
super.paintComponent(g);
}
public void setup(ModelRoot model, RenderersRoot vl,
Action closeAction) {
this.w = model.getWorld();
}
}
Methods:
MethodJavadoc
paintComponent
setup
jfreerails.client.view.DetailMapRenderer
Javadoc:
/** * Draws the main map, that is the terrain, track, trains, station names etc. * * @author Luke */
Source code:
/**
* Draws the main map, that is the terrain, track, trains, station names etc.
*
* @author Luke
*/
public class DetailMapRenderer implements MapRenderer {
private static final boolean OSXWorkaround = (System
.getProperty("OSXWorkaround") != null);
private final MapLayerRenderer background;
private final Dimension mapSizeInPixels;
private final OverHeadTrainView trainsview;
private final StationRadiusRenderer stationRadius;
private final BuildTrackRenderer buildTrackRenderer;
private final BuildTrackController buildTrackController;
private final Painter stationBoxes;
public DetailMapRenderer(ReadOnlyWorld world, RenderersRoot rr,
ModelRoot modelRoot) {
trainsview = new OverHeadTrainView(world, rr, modelRoot);
MapBackgroundRender render = new MapBackgroundRender(world, rr,
modelRoot);
if (OSXWorkaround) {
// Don't buffer the mapviews background.
background = render;
} else {
background = new SquareTileBackgroundRenderer(render);
}
Dimension mapSize = new Dimension(world.getMapWidth(), world
.getMapHeight());
mapSizeInPixels = new Dimension(mapSize.width * Constants.TILE_SIZE,
mapSize.height * Constants.TILE_SIZE);
stationRadius = new StationRadiusRenderer(modelRoot);
buildTrackRenderer = new BuildTrackRenderer(rr, modelRoot);
buildTrackController = new BuildTrackController(world, modelRoot);
stationBoxes = new StationBoxRenderer(world, rr, modelRoot);
}
public StationRadiusRenderer getStationRadius() {
return stationRadius;
}
public BuildTrackController getBuildTrackController() {
return buildTrackController;
}
public float getScale() {
return Constants.TILE_SIZE;
}
public Dimension getMapSizeInPixels() {
return mapSizeInPixels;
}
public TrainRenderer getTrainRenderer() {
return this.trainsview.getTrainRenderer();
}
public void paintTile(Graphics g, int tileX, int tileY) {
background.paintTile(g, tileX, tileY);
trainsview.paint((Graphics2D) g);
stationRadius.paint((Graphics2D) g);
stationBoxes.paint((Graphics2D) g);
buildTrackRenderer.paint((Graphics2D) g);
}
public void refreshTile(int x, int y) {
background.refreshTile(x, y);
}
public void paintRect(Graphics g, Rectangle visibleRect) {
background.paintRect(g, visibleRect);
trainsview.paint((Graphics2D) g);
stationRadius.paint((Graphics2D) g);
stationBoxes.paint((Graphics2D) g);
buildTrackRenderer.paint((Graphics2D) g);
}
public void refreshAll() {
background.refreshAll();
}
}
Methods:
MethodJavadoc
getBuildTrackController
getMapSizeInPixels
getScale
getStationRadius
getTrainRenderer
paintRect
paintTile
refreshAll
refreshTile
jfreerails.client.view.DialogueBoxController
Javadoc:
/** * This class is responsible for displaying dialogue boxes, adding borders to * them as appropriate, and returning focus to the last focus owner after a * dialogue box has been closed. It is also responsible for adding components * that need to update in response to moves to the MoveChainFork. Currently * dialogue boxes are not separate windows. Instead, they are drawn on the modal * layer of the main JFrames LayerPlane. This allows dialogue boxes with * transparent regions to be used. * * @author lindsal8 * @author smackay */
Source code:
/**
* This class is responsible for displaying dialogue boxes, adding borders to
* them as appropriate, and returning focus to the last focus owner after a
* dialogue box has been closed. It is also responsible for adding components
* that need to update in response to moves to the MoveChainFork. Currently
* dialogue boxes are not separate windows. Instead, they are drawn on the modal
* layer of the main JFrames LayerPlane. This allows dialogue boxes with
* transparent regions to be used.
*
* @author lindsal8
* @author smackay
*/
public class DialogueBoxController implements WorldListListener {
private static final Logger logger = Logger
.getLogger(DialogueBoxController.class.getName());
private final JButton closeButton = new JButton("Close");
private SelectEngineJPanel selectEngine;
private final MyGlassPanel glassPanel;
private NewsPaperJPanel newspaper;
private SelectWagonsJPanel selectWagons;
private HtmlJPanel showControls;
private HtmlJPanel about;
private HtmlJPanel how2play;
private HtmlJPanel javaProperties;
private TerrainInfoJPanel terrainInfo;
private StationInfoJPanel stationInfo;
private TrainDialogueJPanel trainDialogueJPanel;
private ReadOnlyWorld world;
private ModelRootImpl modelRoot;
private RenderersRoot vl;
private Component defaultFocusOwner = null;
private final JFrame frame;
private JInternalFrame dialogueJInternalFrame;
/**
* Use this Action to close a dialogue without performing any other
* action.
*/
private final Action closeCurrentDialogue = new AbstractAction("Close") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
closeContent();
}
};
private final Action selectEngineAction = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
showSelectWagons();
}
};
private final ActionListener trainDetailsButtonActionListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
showTrainList();
}
};
private final Action selectWagonsAction = new AbstractAction("Next") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
WorldIterator wi = new NonNullElements(KEY.STATIONS, modelRoot
.getWorld(), modelRoot.getPrincipal());
if (wi.next()) {
StationModel station = (StationModel) wi.getElement();
ImList<PlannedTrain> before = station.getProduction();
int engineType = selectEngine.getEngineType();
int[] wagonTypes = selectWagons.getWagons();
ImList<PlannedTrain> after = new ImList<PlannedTrain>(
new PlannedTrain(engineType, wagonTypes));
Move m = new ChangeProductionAtEngineShopMove(before, after, wi
.getIndex(), modelRoot.getPrincipal());
modelRoot.doMove(m);
}
closeContent();
}
};
public DialogueBoxController(JFrame frame, ModelRootImpl mr) {
this.frame = frame;
modelRoot = mr;
// Setup glass panel..
glassPanel = new MyGlassPanel();
glassPanel.setSize(frame.getSize());
frame.getLayeredPane().add(glassPanel, JLayeredPane.MODAL_LAYER);
glassPanel.revalidate();
glassPanel.setVisible(false);
// We need to resize the glass panel when its parent resizes.
frame.getLayeredPane().addComponentListener(
new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(
java.awt.event.ComponentEvent evt) {
glassPanel.setSize(glassPanel.getParent().getSize());
glassPanel.revalidate();
}
});
closeButton.addActionListener(closeCurrentDialogue);
showControls = new HtmlJPanel(DialogueBoxController.class
.getResource("/jfreerails/client/view/game_controls.html"));
about = new HtmlJPanel(DialogueBoxController.class
.getResource("/jfreerails/client/view/about.htm"));
how2play = new HtmlJPanel(DialogueBoxController.class
.getResource("/jfreerails/client/view/how_to_play.htm"));
terrainInfo = new TerrainInfoJPanel();
stationInfo = new StationInfoJPanel();
javaProperties = new HtmlJPanel(ShowJavaProperties
.getPropertiesHtmlString());
Dimension d = javaProperties.getPreferredSize();
d.width += 50;
javaProperties.setPreferredSize(d);
newspaper = new NewsPaperJPanel();
selectWagons = new SelectWagonsJPanel();
selectEngine = new SelectEngineJPanel();
trainDialogueJPanel = new TrainDialogueJPanel();
}
/**
* Called when a new game is started or a game is loaded.
* <p>
* <b>Be extremely careful with the references of objects allocated in this
* method to avoid memory leaks - see bug 967677 (OutOfMemoryError after
* starting several new games). </b>
* </p>
*/
public void setup(ModelRootImpl mr, RenderersRoot vl) {
this.modelRoot = mr;
this.vl = vl;
modelRoot.addListListener(this); // When a new train gets built, we
// show the train info etc
this.world = modelRoot.getWorld();
if (world == null)
throw new NullPointerException();
if (vl == null)
throw new NullPointerException();
// Setup the various dialogue boxes.
// setup the terrain info dialogue.
terrainInfo.setup(world, vl);
// setup the supply and demand at station dialogue.
stationInfo.setup(modelRoot, vl, this.closeCurrentDialogue);
modelRoot.addListListener(stationInfo);
// setup the 'show controls' dialogue
showControls.setup(this.modelRoot, vl, this.closeCurrentDialogue);
about.setup(this.modelRoot, vl, this.closeCurrentDialogue);
how2play.setup(this.modelRoot, vl, this.closeCurrentDialogue);
javaProperties.setup(this.modelRoot, vl, this.closeCurrentDialogue);
// Set up train orders dialogue
// trainScheduleJPanel = new TrainScheduleJPanel();
// trainScheduleJPanel.setup(w, vl);
// moveChainFork.add(trainScheduleJPanel);
// Set up select engine dialogue.
selectEngine.setCancelButtonActionListener(this.closeCurrentDialogue);
selectEngine.setup(modelRoot, vl, selectEngineAction);
newspaper.setup(modelRoot, vl, closeCurrentDialogue);
selectWagons.setup(modelRoot, vl, selectWagonsAction);
trainDialogueJPanel.setup(modelRoot, vl, this.closeCurrentDialogue);
modelRoot.addListListener(trainDialogueJPanel);
trainDialogueJPanel
.setTrainDetailsButtonActionListener(trainDetailsButtonActionListener);
trainDialogueJPanel
.setCancelButtonActionListener(this.closeCurrentDialogue);
}
public void showSaveGame(){
SaveGameJPanel saveGameJPanel = new SaveGameJPanel();
saveGameJPanel.setup(modelRoot, vl, this.closeCurrentDialogue);
showContent(saveGameJPanel);
}
public void showSelectSavedGame2Load(){
Message2Server refreshGames = new RefreshListOfGamesMessage2Server(2);
modelRoot.sendCommand(refreshGames);
LoadGameJPanel loadGameJPane = new LoadGameJPanel();
loadGameJPane.setup(modelRoot, vl, this.closeCurrentDialogue);
showContent(loadGameJPane);
}
public void showTrainOrders() {
WorldIterator wi = new NonNullElements(KEY.TRAINS, world, modelRoot
.getPrincipal());
if (!wi.next()) {
modelRoot.setProperty(Property.QUICK_MESSAGE, "Cannot"
+ " show train orders since there are no" + " trains!");
} else {
trainDialogueJPanel.display(wi.getIndex());
this.showContent(trainDialogueJPanel);
}
}
public void showSelectEngine() {
WorldIterator wi = new NonNullElements(KEY.STATIONS, world, modelRoot
.getPrincipal());
if (!wi.next()) {
modelRoot.setProperty(Property.QUICK_MESSAGE, "Can't"
+ " build train since there are no stations");
} else {
showContent(selectEngine);
}
}
public void showGameControls() {
showContent(this.showControls);
}
public void showIncomeStatement() {
IncomeStatementHtmlJPanel bs = new IncomeStatementHtmlJPanel();
bs.setup(this.modelRoot, vl, this.closeCurrentDialogue);
this.showContent(bs);
}
public void showBalanceSheet() {
BalanceSheetHtmlJPanel bs = new BalanceSheetHtmlJPanel();
bs.setup(this.modelRoot, vl, this.closeCurrentDialogue);
this.showContent(bs);
}
public void showReportBug(){
CopyableTextJPanel ct = new CopyableTextJPanel();
ct.setText(ReportBugTextGenerator.genText());
showContent(ct);
}
public void showBrokerScreen() {
// this is Creating a BrokerScreen Internal Frame in the Main Frame
BrokerScreenHtmlJFrame brokerScreenHtmlJFrame = new BrokerScreenHtmlJFrame();
brokerScreenHtmlJFrame.setup(this.modelRoot, vl,
this.closeCurrentDialogue);
brokerScreenHtmlJFrame.setFrameIcon(null);
showContent(brokerScreenHtmlJFrame);
}
// Shows the Exit Dialog -- @author SonnyZ
public void showExitDialog() {
ConfirmExitJPanel bs = new ConfirmExitJPanel();
bs.setup(this.modelRoot, vl, this.closeCurrentDialogue);
this.showContent(bs);
}
public void showAbout() {
showContent(this.about);
}
public void showHow2Play() {
showContent(this.how2play);
}
public void showJavaProperties() {
showContent(javaProperties);
}
public void showSelectWagons() {
selectWagons.resetSelectedWagons();
selectWagons.setEngineType(selectEngine.getEngineType());
showContent(selectWagons);
}
public void showTerrainInfo(int terrainType) {
this.terrainInfo.setTerrainType(terrainType);
showContent(terrainInfo);
}
public void showTerrainInfo(int x, int y) {
FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
int terrainType = tile.getTerrainTypeID();
showTerrainInfo(terrainType);
}
public void showStationInfo(int stationNumber) {
try {
stationInfo.setStation(stationNumber);
showContent(stationInfo);
} catch (NoSuchElementException e) {
logger.warning("Station " + stationNumber + " does not exist!");
}
}
public void showTrainOrders(int trainId) {
closeContent();
if (trainId != -1) {
trainDialogueJPanel.display(trainId);
showContent(trainDialogueJPanel);
}
}
public void showTrainList() {
if (world.size(modelRoot.getPrincipal(), KEY.TRAINS) > 0) {
final TrainListJPanel trainList = new TrainListJPanel();
trainList.setup(modelRoot, vl, closeCurrentDialogue);
trainList.setShowTrainDetailsActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int id = trainList.getSelectedTrainID();
showTrainOrders(id);
}
});
showContent(trainList);
} else {
modelRoot.setProperty(Property.QUICK_MESSAGE, "There are"
+ " no trains to display!");
}
}
public void showNetworthGraph() {
final NetWorthGraphJPanel worthGraph = new NetWorthGraphJPanel();
worthGraph.setup(modelRoot, vl, closeCurrentDialogue);
showContent(worthGraph);
}
public void showLeaderBoard() {
LeaderBoardJPanel leaderBoardJPanel = new LeaderBoardJPanel();
leaderBoardJPanel.setup(modelRoot, vl, closeCurrentDialogue);
showContent(leaderBoardJPanel);
}
public void showContent(JComponent component) {
closeContent();
JComponent contentPanel;
if (component instanceof JInternalFrame) {
dialogueJInternalFrame = (JInternalFrame) component;
} else {
if (!(component instanceof View)) {
contentPanel = new javax.swing.JPanel();
contentPanel.setLayout(new java.awt.GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.insets = new Insets(7, 7, 7, 7);
contentPanel.add(component, constraints);
constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 1;
constraints.insets = new Insets(7, 7, 7, 7);
contentPanel.add(closeButton, constraints);
} else {
contentPanel = component;
}
dialogueJInternalFrame = new JInternalFrame();
dialogueJInternalFrame.setFrameIcon(null);
dialogueJInternalFrame.getContentPane().add(contentPanel);
dialogueJInternalFrame.pack();
}
/*
* Make sure the size of the dialogue does not exceed the size of the
* frames content pane.
*/
int parentWidth = frame.getContentPane().getWidth();
int parentHeight = frame.getContentPane().getHeight();
Dimension size = dialogueJInternalFrame.getSize();
if (size.width > parentWidth) {
size.width = parentWidth;
}
if (size.height > parentHeight) {
size.height = parentHeight;
}
dialogueJInternalFrame.setSize(size);
dialogueJInternalFrame.setLocation(
(frame.getWidth() - dialogueJInternalFrame.getWidth()) / 2,
(frame.getHeight() - dialogueJInternalFrame.getHeight()) / 2);
frame.getLayeredPane().add(dialogueJInternalFrame,
JLayeredPane.MODAL_LAYER);
dialogueJInternalFrame.setVisible(true);
}
public void closeContent() {
if (null != dialogueJInternalFrame) {
dialogueJInternalFrame.setVisible(false);
frame.getLayeredPane().remove(dialogueJInternalFrame);
dialogueJInternalFrame.dispose();
}
if (null != defaultFocusOwner) {
defaultFocusOwner.requestFocus();
}
}
public void setDefaultFocusOwner(Component defaultFocusOwner) {
this.defaultFocusOwner = defaultFocusOwner;
}
public void showStationOrTerrainInfo(int x, int y) {
FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
TrackRule trackRule = tile.getTrackPiece().getTrackRule();
FreerailsPrincipal principal = modelRoot.getPrincipal();
if (trackRule.isStation()
&& tile.getTrackPiece().getOwnerID() == world.getID(principal)) {
for (int i = 0; i < world.size(principal, KEY.STATIONS); i++) {
StationModel station = (StationModel) world.get(principal,
KEY.STATIONS, i);
if (null != station && station.x == x && station.y == y) {
this.showStationInfo(i);
return;
}
}
throw new IllegalStateException("Couldn't find station at " + x
+ ", " + y);
}
this.showTerrainInfo(x, y);
}
public void listUpdated(KEY key, int index, FreerailsPrincipal principal) {
// do nothing
}
public void itemAdded(KEY key, int index, FreerailsPrincipal principal) {
/*
* Fix for: 910138 After building a train display train orders 910143
* After building station show supply and demand
*/
boolean rightPrincipal = principal
.equals(this.modelRoot.getPrincipal());
if (KEY.TRAINS == key && rightPrincipal) {
this.showTrainOrders(index);
} else if (KEY.STATIONS == key && rightPrincipal) {
this.showStationInfo(index);
}
}
public void itemRemoved(KEY key, int index, FreerailsPrincipal principal) {
// do nothing
}
}
Methods:
MethodJavadoc
closeContent
itemAdded
itemRemoved
listUpdated
setDefaultFocusOwner
setup/**
showAbout
showBalanceSheet/**
showBrokerScreen
showContent
showExitDialog
showGameControls
showHow2Play
showIncomeStatement
showJavaProperties
showLeaderBoard
showNetworthGraph
showReportBug
showSaveGame
showSelectEngine
showSelectSavedGame2Load
showSelectWagons
showStationInfo
showStationOrTerrainInfo
showTerrainInfo/**
showTerrainInfo
showTrainList
showTrainOrders
showTrainOrders
jfreerails.client.view.DisplayModesComboBoxModels
Javadoc:
/** * ComboBoxModel that provides access to the screen resolutions and bit depths * available. * * @author Luke Lindsay */
Source code:
/**
* ComboBoxModel that provides access to the screen resolutions and bit depths
* available.
*
* @author Luke Lindsay
*/
public class DisplayModesComboBoxModels implements javax.swing.ComboBoxModel {
private final GraphicsConfiguration defaultConfiguration = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
private final ArrayList<MyDisplayMode> modes = new ArrayList<MyDisplayMode>();
private MyDisplayMode selection;
public DisplayModesComboBoxModels() {
DisplayMode currentMode = defaultConfiguration.getDevice()
.getDisplayMode();
selection = new MyDisplayMode(currentMode);
DisplayMode[] displayModes = defaultConfiguration.getDevice()
.getDisplayModes();
for (int i = 0; i < displayModes.length; i++) {
MyDisplayMode mode = new MyDisplayMode(displayModes[i]);
modes.add(mode);
}
}
/**
* Permanently removes from the list in this object any display modes with
* width, height, or bitdepth below the specified values.
*/
public void removeDisplayModesBelow(int width, int height, int bitdepth) {
Iterator<MyDisplayMode> it = modes.iterator();
while (it.hasNext()) {
MyDisplayMode mode = it.next();
DisplayMode displayMode = mode.displayMode;
final boolean tooNarrow = displayMode.getWidth() < width;
final boolean tooShort = displayMode.getHeight() < height;
/*
* Note, displayMode.getBitDepth() may return
* DisplayMode.BIT_DEPTH_MULTI, which is -1.
*/
final boolean tooFewColours = (displayMode.getBitDepth() < bitdepth)
&& (displayMode.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI);
if (tooNarrow || tooShort || tooFewColours) {
it.remove();
}
}
}
public Object getSelectedItem() {
return selection;
}
public void setSelectedItem(Object anItem) {
selection = (MyDisplayMode) anItem;
}
public void addListDataListener(javax.swing.event.ListDataListener l) {
}
public MyDisplayMode getElementAt(int index) {
return modes.get(index);
}
public int getSize() {
return modes.size();
}
public void removeListDataListener(javax.swing.event.ListDataListener l) {
}
}
Methods:
MethodJavadoc
addListDataListener
getElementAt
getSelectedItem
getSize
removeDisplayModesBelow/**
removeListDataListener
setSelectedItem
jfreerails.client.view.FreerailsCursor
Javadoc:
/** * Paints the cursor on the map, note the cursor's position is stored on the * ModelRoot under the key CURSOR_POSITION. * * @author Luke */
Source code:
/**
* Paints the cursor on the map, note the cursor's position is stored on the
* ModelRoot under the key CURSOR_POSITION.
*
* @author Luke
*/
final public class FreerailsCursor {
private final Image buildTrack, upgradeTrack, removeTrack, infoMode;
private final ModelRoot modelRoot;
/** The location of the cursor last time paintCursor(.) was called. */
private ImPoint lastCursorPosition = new ImPoint();
/** The time in ms the cursor arrived at its current position. */
private long timeArrived = 0;
/**
* Creates a new FreerailsCursor.
*
* @throws IOException
*/
public FreerailsCursor(ModelRoot mr, RenderersRoot rr) throws IOException {
this.modelRoot = mr;
modelRoot.setProperty(ModelRoot.Property.CURSOR_MESSAGE, null);
buildTrack = rr.getImage("cursor/buildtrack.png");
upgradeTrack = rr.getImage("cursor/upgradetrack.png");
removeTrack = rr.getImage("cursor/removetrack.png");
infoMode = rr.getImage("cursor/infomode.png");
}
/**
* Paints the cursor. The method calculates position to paint it based on
* the tile size and the cursor's map position.
*
* @param g
* The graphics object to paint the cursor on.
* @param tileSize
* The dimensions of a tile.
*/
public void paintCursor(Graphics g, Dimension tileSize) {
Graphics2D g2 = (Graphics2D) g;
TrackMoveProducer.BuildMode buildMode = (TrackMoveProducer.BuildMode) modelRoot
.getProperty(ModelRoot.Property.TRACK_BUILDER_MODE);
ImPoint cursorMapPosition = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.CURSOR_POSITION);
/* Has the cursor moved since we last painted it? */
if (!cursorMapPosition.equals(lastCursorPosition)) {
lastCursorPosition = cursorMapPosition;
timeArrived = System.currentTimeMillis();
}
int x = cursorMapPosition.x * tileSize.width;
int y = cursorMapPosition.y * tileSize.height;
Image cursor = null;
switch (buildMode) {
case BUILD_TRACK:
cursor = buildTrack;
break;
case REMOVE_TRACK:
cursor = removeTrack;
break;
case UPGRADE_TRACK:
cursor = upgradeTrack;
break;
case IGNORE_TRACK:
cursor = infoMode;
break;
case BUILD_STATION:
cursor = buildTrack;
break;
}
Boolean b = (Boolean) modelRoot
.getProperty(ModelRoot.Property.IGNORE_KEY_EVENTS);
long time = System.currentTimeMillis() - timeArrived;
boolean show = ((time / 500) % 2) == 0;
if (show && !b.booleanValue()) {
g.drawImage(cursor, x, y, null);
}
// Second, draw a message below the cursor if appropriate.
String message = (String) modelRoot
.getProperty(ModelRoot.Property.CURSOR_MESSAGE);
if (null != message && !message.equals("")) {
int fontSize = 12;
Font font = new Font("Arial", 0, fontSize);
FontRenderContext frc = g2.getFontRenderContext();
TextLayout layout = new TextLayout(message, font, frc);
// We want the message to be centered below the cursor.
float visibleAdvance = layout.getVisibleAdvance();
float textX = (x + (tileSize.width / 2) - (visibleAdvance / 2));
float textY = y + tileSize.height + fontSize + 5;
g.setColor(java.awt.Color.white);
layout.draw(g2, textX, textY);
}
// Draw a big white dot at the target point.
ImPoint targetPoint = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.THINKING_POINT);
if (null != targetPoint) {
time = System.currentTimeMillis();
int dotSize;
if ((time % 500) > 250) {
dotSize = BuildTrackRenderer.BIG_DOT_WIDTH;
} else {
dotSize = BuildTrackRenderer.SMALL_DOT_WIDTH;
}
g.setColor(Color.WHITE);
x = targetPoint.x * tileSize.width + (tileSize.width - dotSize) / 2;
y = targetPoint.y * tileSize.width + (tileSize.height - dotSize)
/ 2;
g.fillOval(x, y, dotSize, dotSize);
}
}
}
Methods:
MethodJavadoc
paintCursor/**
jfreerails.client.view.HtmlJPanel
Javadoc:
/** * This JPanel displays a HTML document read from a URL. * * @author Luke */
Source code:
/**
* This JPanel displays a HTML document read from a URL.
*
* @author Luke
*/
public class HtmlJPanel extends javax.swing.JPanel implements View {
private static final long serialVersionUID = 4120848850266371126L;
private static final Logger logger = Logger.getLogger(HtmlJPanel.class
.getName());
HtmlJPanel() {
initComponents();
}
public HtmlJPanel(URL url) {
initComponents();
setHtml(loadText(url));
}
public HtmlJPanel(URL url, HashMap context) {
initComponents();
String template = loadText(url);
String populatedTemplate = populateTokens(template, context);
setHtml(populatedTemplate);
}
public HtmlJPanel(String html) {
initComponents();
setHtml(html);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
htmlJLabel = new javax.swing.JLabel();
done = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
setMinimumSize(new java.awt.Dimension(400, 300));
jScrollPane1
.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
htmlJLabel.setFont(new java.awt.Font("Dialog", 0, 12));
htmlJLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
jScrollPane1.setViewportView(htmlJLabel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(jScrollPane1, gridBagConstraints);
done.setText("Close");
done.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
doneActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(done, gridBagConstraints);
}// GEN-END:initComponents
private void doneActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_doneActionPerformed
// TODO add your handling code here:
}// GEN-LAST:event_doneActionPerformed
public void setup(ModelRoot m, RenderersRoot vl,
Action closeAction) {
this.done.setAction(closeAction);
}
/** Load the help text from file. */
String loadText(final URL htmlUrl) {
try {
InputStream in = htmlUrl.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
new DataInputStream(in)));
String line;
String text = "";
while ((line = br.readLine()) != null) {
text = text + line;
}
return text;
} catch (Exception e) {
e.printStackTrace();
logger.warning(htmlUrl.toString());
return "Couldn't read: " + htmlUrl;
}
}
void setHtml(String s) {
htmlJLabel.setText(s);
}
static String populateTokens(String template, Object context) {
StringTokenizer tokenizer = new StringTokenizer(template, "$");
String output = "";
while (tokenizer.hasMoreTokens()) {
output += tokenizer.nextToken();
if (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
String value;
if (context instanceof HashMap) {
value = (String) ((HashMap) context).get(token);
} else {
try {
StringTokenizer t2 = new StringTokenizer(token, ".");
value = null;
Object o = context;
while (t2.hasMoreTokens()) {
String subToken = t2.nextToken();
Field field = o.getClass().getField(subToken);
o = field.get(o);
}
value = o.toString();
} catch (Exception e) {
e.printStackTrace();
throw new NoSuchElementException(token);
}
}
output += value;
}
}
return output;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton done;
private javax.swing.JLabel htmlJLabel;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
doneActionPerformed
initComponents/**
loadText/** Load the help text from file. */
populateTokens
setHtml
setup
jfreerails.client.view.IncomeStatementGenerator
Javadoc:
/** * Generates the income statement- note, its fields are read using reflection so * don't change their names. * * @author Luke * */
Source code:
/**
* Generates the income statement- note, its fields are read using reflection so
* don't change their names.
*
* @author Luke
*
*/
public class IncomeStatementGenerator {
GameTime from;
GameTime to;
final ReadOnlyWorld w;
final FreerailsPrincipal principal;
private int startyear = 0;
private GameCalendar cal;
public Money mailTotal;
public Money passengersTotal;
public Money fastFreightTotal;
public Money slowFreightTotal;
public Money bulkFreightTotal;
public Money interestTotal;
public Money trainMaintenanceTotal;
public Money trackMaintenanceTotal;
public Money stationMaintenanceTotal;
public Money profitTotal;
public Money mailYtd;
public Money passengersYtd;
public Money fastFreightYtd;
public Money slowFreightYtd;
public Money bulkFreightYtd;
public Money interestYtd;
public Money trainMaintenanceYtd;
public Money trackMaintenanceYtd;
public Money stationMaintenanceYtd;
public Money profitYtd;
public String year;
IncomeStatementGenerator(ReadOnlyWorld w, FreerailsPrincipal principal) {
this.w = w;
this.principal = principal;
cal = (GameCalendar) w.get(ITEM.CALENDAR);
// Income from cargo delivery
mailTotal = calRevenue(Categories.Mail);
passengersTotal = calRevenue(Categories.Passengers);
fastFreightTotal = calRevenue(Categories.Fast_Freight);
slowFreightTotal = calRevenue(Categories.Slow_Freight);
bulkFreightTotal = calRevenue(Categories.Bulk_Freight);
// Expenses.
interestTotal = calTotal(INTEREST_CHARGE);
trainMaintenanceTotal = calTotal(TRAIN_MAINTENANCE);
trackMaintenanceTotal = calTotal(TRACK_MAINTENANCE);
stationMaintenanceTotal = calTotal(STATION_MAINTENANCE);
/*
* Note, expenses are stored as negative values so we just add
* everything up.
*/
long profit = mailTotal.getAmount() + passengersTotal.getAmount()
+ fastFreightTotal.getAmount() + slowFreightTotal.getAmount()
+ bulkFreightTotal.getAmount() + interestTotal.getAmount()
+ trainMaintenanceTotal.getAmount()
+ trackMaintenanceTotal.getAmount()
+ stationMaintenanceTotal.getAmount();
profitTotal = new Money(profit);
GameTime time = w.currentTime();
startyear = cal.getYear(time.getTicks());
year = String.valueOf(startyear);
// Income from cargo delivery
mailYtd = calRevenue(Categories.Mail);
passengersYtd = calRevenue(Categories.Passengers);
fastFreightYtd = calRevenue(Categories.Fast_Freight);
slowFreightYtd = calRevenue(Categories.Slow_Freight);
bulkFreightYtd = calRevenue(Categories.Bulk_Freight);
// Expenses.
interestYtd = calTotal(INTEREST_CHARGE);
trainMaintenanceYtd = calTotal(TRAIN_MAINTENANCE);
trackMaintenanceYtd = calTotal(TRACK_MAINTENANCE);
stationMaintenanceYtd = calTotal(STATION_MAINTENANCE);
/*
* Note, expenses are stored as negative values so we just add
* everything up.
*/
profit = mailYtd.getAmount() + passengersYtd.getAmount()
+ fastFreightYtd.getAmount() + slowFreightYtd.getAmount()
+ bulkFreightYtd.getAmount() + interestYtd.getAmount()
+ trainMaintenanceYtd.getAmount()
+ trackMaintenanceYtd.getAmount()
+ stationMaintenanceYtd.getAmount();
profitYtd = new Money(profit);
}
/** Calculates the total revenue from the specified cargo type. */
Money calRevenue(Categories cargoCategory) {
long amount = 0;
for (int i = 0; i < w.getNumberOfTransactions(this.principal); i++) {
Transaction t = w.getTransaction(principal, i);
GameTime time = w.getTransactionTimeStamp(principal, i);
if (t instanceof DeliverCargoReceipt
&& cal.getYear(time.getTicks()) >= this.startyear) {
DeliverCargoReceipt dcr = (DeliverCargoReceipt) t;
int cargoType = dcr.getCb().getCargoType();
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, cargoType);
if (ct.getCategory().equals(cargoCategory)) {
amount += dcr.deltaCash().getAmount();
}
}
}
return new Money(amount);
}
Money calTrainRevenue(int trainId) {
long amount = 0;
for (int i = 0; i < w.getNumberOfTransactions(this.principal); i++) {
Transaction t = w.getTransaction(principal, i);
GameTime time = w.getTransactionTimeStamp(principal, i);
if (t instanceof DeliverCargoReceipt
&& cal.getYear(time.getTicks()) >= this.startyear) {
DeliverCargoReceipt dcr = (DeliverCargoReceipt) t;
if (dcr.getTrainId() == trainId) {
amount += dcr.deltaCash().getAmount();
}
}
}
return new Money(amount);
}
private Money calTotal(Transaction.Category transactionCategory) {
long amount = 0;
for (int i = 0; i < w.getNumberOfTransactions(this.principal); i++) {
Transaction t = w.getTransaction(principal, i);
GameTime time = w.getTransactionTimeStamp(principal, i);
if (t.getCategory() == transactionCategory
&& cal.getYear(time.getTicks()) >= this.startyear) {
amount += t.deltaCash().getAmount();
}
}
return new Money(amount);
}
}
Methods:
MethodJavadoc
calRevenue/** Calculates the total revenue from the specified cargo type. */
calTotal
calTrainRevenue
jfreerails.client.view.IncomeStatementHtmlJPanel
Javadoc:
/** * A HtmlJPanel that displays the income statement. * * @author Luke * */
Source code:
/**
* A HtmlJPanel that displays the income statement.
*
* @author Luke
*
*/
public class IncomeStatementHtmlJPanel extends HtmlJPanel implements View {
private static final long serialVersionUID = 3257846588885120057L;
private String template;
private int lastNumTransactions = 0;
private ModelRoot modelRoot;
public IncomeStatementHtmlJPanel() {
super();
URL url = IncomeStatementHtmlJPanel.class
.getResource("/jfreerails/client/view/income_statement.htm");
template = loadText(url);
}
@Override
public void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
super.setup(modelRoot, vl, closeAction);
this.modelRoot = modelRoot;
updateHtml();
}
private void updateHtml() {
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
IncomeStatementGenerator balanceSheetGenerator = new IncomeStatementGenerator(
world, playerPrincipal);
String populatedTemplate = populateTokens(template,
balanceSheetGenerator);
setHtml(populatedTemplate);
}
@Override
protected void paintComponent(Graphics g) {
/* Check to see if the text needs updating before painting. */
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
int currentNumberOfTransactions = world
.getNumberOfTransactions(playerPrincipal);
if (currentNumberOfTransactions != lastNumTransactions) {
updateHtml();
}
super.paintComponent(g);
}
}
Methods:
MethodJavadoc
paintComponent
setup
updateHtml
jfreerails.client.view.KeyCode2OneTileMoveVector
Javadoc:
/** * Maps keys to OneTileMoveVectors. * * @author Luke * */
Source code:
/**
* Maps keys to OneTileMoveVectors.
*
* @author Luke
*
*/
public class KeyCode2OneTileMoveVector {
private static final HashMap<Integer, Step> keycode2vector = new HashMap<Integer, Step>();
static {
// Set up key mappings...
// Num pad with num lock on
keycode2vector.put(new Integer(KeyEvent.VK_NUMPAD1), Step.SOUTH_WEST);
keycode2vector.put(new Integer(KeyEvent.VK_NUMPAD2), Step.SOUTH);
keycode2vector.put(new Integer(KeyEvent.VK_NUMPAD3), Step.SOUTH_EAST);
keycode2vector.put(new Integer(KeyEvent.VK_NUMPAD4), Step.WEST);
keycode2vector.put(new Integer(KeyEvent.VK_NUMPAD6), Step.EAST);
keycode2vector.put(new Integer(KeyEvent.VK_NUMPAD7), Step.NORTH_WEST);
keycode2vector.put(new Integer(KeyEvent.VK_NUMPAD8), Step.NORTH);
keycode2vector.put(new Integer(KeyEvent.VK_NUMPAD9), Step.NORTH_EAST);
// Num pad with num lock off
keycode2vector.put(new Integer(KeyEvent.VK_END), Step.SOUTH_WEST);
keycode2vector.put(new Integer(KeyEvent.VK_DOWN), Step.SOUTH);
keycode2vector.put(new Integer(KeyEvent.VK_PAGE_DOWN), Step.SOUTH_EAST);
keycode2vector.put(new Integer(KeyEvent.VK_LEFT), Step.WEST);
keycode2vector.put(new Integer(KeyEvent.VK_RIGHT), Step.EAST);
keycode2vector.put(new Integer(KeyEvent.VK_HOME), Step.NORTH_WEST);
keycode2vector.put(new Integer(KeyEvent.VK_UP), Step.NORTH);
keycode2vector.put(new Integer(KeyEvent.VK_PAGE_UP), Step.NORTH_EAST);
}
/** Returns the OneTileMoveVector that is mapped to the specified keycode. */
public static Step getInstanceMappedToKey(int keycode)
throws NoSuchElementException {
Integer integer = new Integer(keycode);
if (!keycode2vector.containsKey(integer)) {
throw new NoSuchElementException(String.valueOf(keycode));
}
return keycode2vector.get(integer);
}
}
Methods:
MethodJavadoc
getInstanceMappedToKey/** Returns the OneTileMoveVector that is mapped to the specified keycode. */
jfreerails.client.view.LeaderBoardJPanel
Javadoc:
/** * A JPanel that displays the details of the players ordered by net worth. * * @author Luke */
Source code:
/**
* A JPanel that displays the details of the players ordered by net worth.
*
* @author Luke
*/
public class LeaderBoardJPanel extends JPanel implements View {
private static final long serialVersionUID = 3258131375298066229L;
private JList playersList = null;
private ActionListener submitButtonCallBack = null;
private Vector<PlayerDetails> values;
/**
* This method initializes
*/
public LeaderBoardJPanel() {
super();
values = new Vector<PlayerDetails>();
Random rand = new Random();
for (int i = 0; i < 5; i++) {
PlayerDetails p = new PlayerDetails();
p.networth = new Money(rand.nextInt(100));
values.add(p);
}
initialize();
}
/**
* This method initializes this
*/
private void initialize() {
this.add(getPlayersList(), null);
java.awt.event.MouseAdapter mouseAdapter = new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
if (null == submitButtonCallBack) {
System.err.println("mouseClicked");
} else {
submitButtonCallBack.actionPerformed(new ActionEvent(
this, 0, null));
}
}
};
this.addMouseListener(mouseAdapter);
this.playersList.addMouseListener(mouseAdapter);
this.setSize(getPreferredSize());
}
/**
* This method initializes jList
*
* @return javax.swing.JList
*/
private JList getPlayersList() {
if (playersList == null) {
playersList = new JList();
playersList
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
playersList.setRequestFocusEnabled(false);
playersList.setEnabled(true);
Collections.sort(values);
playersList.setListData(values);
}
return playersList;
}
public void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
ReadOnlyWorld w = modelRoot.getWorld();
values.clear();
this.submitButtonCallBack = closeAction;
for (int player = 0; player < w.getNumberOfPlayers(); player++) {
PlayerDetails details = new PlayerDetails();
FreerailsPrincipal principal = w.getPlayer(player).getPrincipal();
details.name = principal.getName();
NonNullElements stations = new NonNullElements(KEY.STATIONS, w,
principal);
details.stations = stations.size();
TransactionAggregator networth = new NetWorthCalculator(
w, principal);
details.networth = networth.calculateValue();
values.add(details);
}
Collections.sort(values);
playersList.setListData(values);
setSize(getPreferredSize());
}
/**
* Stores the details a player that are shown on the leaderboard.
*
* @author Luke
*/
static class PlayerDetails implements Comparable<PlayerDetails> {
String name = "player";
Money networth = new Money(0);
int stations = 0;
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(name);
sb.append(", ");
sb.append(networth.toString());
sb.append(" net worth, ");
sb.append(stations);
sb.append(" stations.");
return sb.toString();
}
public int compareTo(PlayerDetails test) {
long l = test.networth.getAmount() - networth.getAmount();
return (int) l;
}
}
} // @jve:decl-index=0:visual-constraint="67,32"
Methods:
MethodJavadoc
getPlayersList/**
initialize/**
setup
jfreerails.client.view.LoadGameJPanel
Javadoc:
/** * * @author Luke */
Source code:
/**
*
* @author Luke
*/
public class LoadGameJPanel extends javax.swing.JPanel implements View {
private static final long serialVersionUID = -6810248272441137826L;
private ImStringList lastFiles;
/** Creates new form LoadGameJPanel */
public LoadGameJPanel() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jLabel1 = new javax.swing.JLabel();
okButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
refreshButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jScrollPane1.setViewportView(jList1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(jScrollPane1, gridBagConstraints);
jLabel1.setText("Please select a game to load.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(jLabel1, gridBagConstraints);
okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(okButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(cancelButton, gridBagConstraints);
refreshButton.setText("Refresh");
refreshButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
refreshButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(refreshButton, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
Message2Server refreshGames = new RefreshListOfGamesMessage2Server(2);
modelRoot.sendCommand(refreshGames);
}//GEN-LAST:event_refreshButtonActionPerformed
private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
}//GEN-LAST:event_formComponentShown
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
if(null != close)
close.actionPerformed(evt);
}//GEN-LAST:event_cancelButtonActionPerformed
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
String filename = (String)jList1.getSelectedValue();
Message2Server message2 = new LoadGameMessage2Server(1,
filename);
modelRoot.sendCommand(message2);
if(null != close)
close.actionPerformed(evt);
}//GEN-LAST:event_okButtonActionPerformed
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
okButton.setEnabled(jList1.getSelectedIndex() != -1);
}//GEN-LAST:event_jList1ValueChanged
public void setup(ModelRoot m, RenderersRoot vl, Action closeAction) {
this.close = closeAction;
modelRoot = m;
updateListOfFiles();
}
private void updateListOfFiles() {
ImStringList files = (ImStringList) modelRoot.getProperty(Property.SAVED_GAMES_LIST);
Object[] saves = new Object[files.size()];
for (int i = 0; i < files.size(); i++) {
saves[i] = files.get(i);
}
jList1.setListData(saves);
okButton.setEnabled(jList1.getSelectedIndex() != -1);
lastFiles = files;
}
@Override
protected void paintComponent(Graphics g) {
ImStringList files = (ImStringList) modelRoot.getProperty(Property.SAVED_GAMES_LIST);
if(!lastFiles.equals(files)){
updateListOfFiles();
}
super.paintComponent(g);
}
ModelRoot modelRoot;
ActionListener close;
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JButton cancelButton;
javax.swing.JLabel jLabel1;
javax.swing.JList jList1;
javax.swing.JScrollPane jScrollPane1;
javax.swing.JButton okButton;
javax.swing.JButton refreshButton;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
cancelButtonActionPerformed/**
formComponentShown
initComponents/** This method is called from within the constructor to
jList1ValueChanged
okButtonActionPerformed
paintComponent
refreshButtonActionPerformed
setup
updateListOfFiles
jfreerails.client.view.MainMapAndOverviewMapMediator
Javadoc:
/** * This class mediates between the main map view and the overview map view. It * does the following:<br> * (1) Updates the rectangle on the overview map when the visible rectangle of * the main map changes.<br> * (2) Updates the main map visible rectangle when the user clicks on the * overview map.<br> * (3) Updates the main map visible rectangle when the user drags the rectangle * on the overview map.<br> * (4) Changes the mouse cursor to indicate that the rectangle on the overview * map is draggable when the mouse moves into the rectangle. * * @author Luke Lindsay * @version 1.0 */
Source code:
/**
* This class mediates between the main map view and the overview map view. It
* does the following:<br>
* (1) Updates the rectangle on the overview map when the visible rectangle of
* the main map changes.<br>
* (2) Updates the main map visible rectangle when the user clicks on the
* overview map.<br>
* (3) Updates the main map visible rectangle when the user drags the rectangle
* on the overview map.<br>
* (4) Changes the mouse cursor to indicate that the rectangle on the overview
* map is draggable when the mouse moves into the rectangle.
*
* @author Luke Lindsay
* @version 1.0
*/
public class MainMapAndOverviewMapMediator extends MouseInputAdapter {
private JComponent overviewMapJPanel;
private JViewport viewport;
private JComponent mainMap;
private Rectangle currentVisRect;
private Point lastMouseLocation = new Point();
private boolean inside = false;
private boolean draggingAndStartedInside = false;
public MainMapAndOverviewMapMediator() {
}
public MainMapAndOverviewMapMediator(JComponent omv, JViewport v,
JComponent mm, Rectangle rect) {
setup(omv, v, mm, rect);
}
public void setup(JComponent omv, JViewport v, JComponent mm, Rectangle rect) {
currentVisRect = rect;
overviewMapJPanel = omv;
viewport = v;
mainMap = mm;
overviewMapJPanel.addMouseMotionListener(this);
overviewMapJPanel.addMouseListener(this);
viewport.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(ChangeEvent e) {
updateObservedRect();
}
});
overviewMapJPanel
.addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(
java.awt.event.ComponentEvent evt) {
updateObservedRect();
}
@Override
public void componentShown(java.awt.event.ComponentEvent evt) {
updateObservedRect();
}
});
}
@Override
public void mouseMoved(MouseEvent evt) {
lastMouseLocation.x = evt.getX();
lastMouseLocation.y = evt.getY();
updateInside(evt);
}
@Override
public void mousePressed(MouseEvent evt) {
if (inside) {
draggingAndStartedInside = true;
}
}
@Override
public void mouseReleased(MouseEvent evt) {
draggingAndStartedInside = false;
}
@Override
public void mouseDragged(MouseEvent evt) {
if (draggingAndStartedInside) {
/*
* Rectangle r= overviewMapJPanel.mainMapVisibleRect;
* r.x+=evt.getX()-lastMouseLocation.x;
* r.y+=evt.getY()-lastMouseLocation.y;
* lastMouseLocation.x=evt.getX(); lastMouseLocation.y=evt.getY();
*
* updateInside(evt); overviewMapJPanel.repaint();
*/
int deltaX = evt.getX() - lastMouseLocation.x;
int deltaY = evt.getY() - lastMouseLocation.y;
lastMouseLocation.x = evt.getX();
lastMouseLocation.y = evt.getY();
// float overviewScale=overviewMapJPanel.getScale();
// float mainMapScale=mainMap.getScale();
int overviewScale = overviewMapJPanel.getPreferredSize().width;
int mainMapScale = mainMap.getWidth();
int scaledDeltaX = (deltaX * mainMapScale / overviewScale);
int scaledDeltaY = (deltaY * mainMapScale / overviewScale);
Rectangle r = mainMap.getVisibleRect();
r.x += scaledDeltaX;
r.y += scaledDeltaY;
mainMap.scrollRectToVisible(r);
updateInside(evt);
}
}
@Override
public void mouseClicked(MouseEvent evt) {
/*
* Rectangle r= overviewMapJPanel.mainMapVisibleRect;
* r.x=evt.getX()-r.width/2; r.y=evt.getY()-r.width/2;
*/
// float overviewScale=overviewMapJPanel.getScale();
// float mainMapScale=mainMap.getScale();
int overviewScale = overviewMapJPanel.getPreferredSize().width;
int mainMapScale = mainMap.getWidth();
int x = (evt.getX() * mainMapScale / overviewScale);
int y = (evt.getY() * mainMapScale / overviewScale);
Rectangle r = mainMap.getVisibleRect();
r.x = x - r.width / 2;
r.y = y - r.height / 2;
mainMap.scrollRectToVisible(r);
updateInside(evt);
}
private void updateInside(MouseEvent evt) {
// Rectangle r= overviewMapJPanel.mainMapVisibleRect;
boolean b = currentVisRect.contains(evt.getX(), evt.getY());
if (b != inside) {
inside = b;
if (inside) {
overviewMapJPanel.setCursor(new Cursor(Cursor.MOVE_CURSOR));
} else {
overviewMapJPanel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
}
private void updateObservedRect() {
Rectangle r = mainMap.getVisibleRect();
// if (!r.equals(this.currentVisRect)) {
// float overviewScale=overviewMapJPanel.getScale();
// float mainMapScale=mainMap.getScale();
int overviewScale = overviewMapJPanel.getPreferredSize().width;
int mainMapScale = mainMap.getWidth();
if (0 != (overviewScale * mainMapScale)) {
// avoid division by zero.
currentVisRect.x = (r.x * overviewScale / mainMapScale);
currentVisRect.y = (r.y * overviewScale / mainMapScale);
currentVisRect.width = (r.width * overviewScale / mainMapScale);
currentVisRect.height = (r.height * overviewScale / mainMapScale);
overviewMapJPanel.repaint();
}
// }
}
}
Methods:
MethodJavadoc
mouseClicked/**
mouseDragged
mouseMoved
mousePressed
mouseReleased/**
setup
updateInside
updateObservedRect
jfreerails.client.view.MapViewJComponent
Javadoc:
/** * JPanel that displays the map and provides methods to handle scrolling. * * @author Luke Lindsay 01 November 2001 */
Source code:
/**
* JPanel that displays the map and provides methods to handle scrolling.
*
* @author Luke Lindsay 01 November 2001
*/
public abstract class MapViewJComponent extends JPanel implements Scrollable,
MapRenderer {
private MapRenderer mapView = new BlankMapRenderer(10);
public MapViewJComponent() {
this.setAutoscrolls(true);
}
public float getScale() {
return getMapView().getScale();
}
@Override
protected void paintComponent(java.awt.Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
java.awt.Rectangle r = this.getVisibleRect();
getMapView().paintRect(g2, r);
}
public int getScrollableUnitIncrement(java.awt.Rectangle rectangle,
int orientation, int direction) {
return (int) getMapView().getScale();
}
public boolean getScrollableTracksViewportWidth() {
return false;
}
public int getScrollableBlockIncrement(java.awt.Rectangle rectangle,
int orientation, int direction) {
if (javax.swing.SwingConstants.VERTICAL == orientation) {
int best = (int) (((rectangle.height / getMapView().getScale()) - 2) * getMapView()
.getScale());
if (best > 0) {
return best;
}
return rectangle.height;
}
float f = ((rectangle.width / getMapView().getScale()) - 2)
* getMapView().getScale();
int best = (int) (f);
if (best > 0) {
return best;
}
return rectangle.width;
}
/**
* Gets the scrollableTracksViewportHeight attribute of the
* MapViewJComponent object.
*
* @return The scrollableTracksViewportHeight value
*/
public boolean getScrollableTracksViewportHeight() {
return false;
}
/**
* Gets the preferredScrollableViewportSize attribute of the
* MapViewJComponent object.
*
* @return The preferredScrollableViewportSize value
*/
public java.awt.Dimension getPreferredScrollableViewportSize() {
return this.getPreferredSize();
}
public void centerOnTile(Point tile) {
float scale = getMapView().getScale();
Rectangle visRect = new Rectangle(this.getVisibleRect());
visRect.x = (int) (tile.x * scale - (visRect.width / 2));
visRect.y = (int) (tile.y * scale - (visRect.height / 2));
this.scrollRectToVisible(visRect);
}
public Dimension getMapSizeInPixels() {
return getMapView().getMapSizeInPixels();
}
@Override
public Dimension getPreferredSize() {
return getMapSizeInPixels();
}
void setMapView(MapRenderer mapView) {
this.mapView = mapView;
}
public MapRenderer getMapView() {
return mapView;
}
}
Methods:
MethodJavadoc
centerOnTile/**
getMapSizeInPixels
getMapView
getPreferredScrollableViewportSize/**
getPreferredSize
getScale
getScrollableBlockIncrement
getScrollableTracksViewportHeight/**
getScrollableTracksViewportWidth
getScrollableUnitIncrement
paintComponent
setMapView
jfreerails.client.view.MapViewJComponentConcrete
Javadoc:
/** * Displays the map, the cursor, and user messages (which are stored on the * ModelRoot under the keys QUICK_MESSAGE and PERMANENT_MESSAGE). * * @author Luke Lindsay * */
Source code:
/**
* Displays the map, the cursor, and user messages (which are stored on the
* ModelRoot under the keys QUICK_MESSAGE and PERMANENT_MESSAGE).
*
* @author Luke Lindsay
*
*/
final public class MapViewJComponentConcrete extends MapViewJComponent
implements ModelRootListener {
private static final long serialVersionUID = 3834868087706236208L;
private static final Font USER_MESSAGE_FONT = new Font("Arial", 0, 12);
private static final Font LARGE_MESSAGE_FONT = new Font("Arial", 0, 24);
/**
* The length of the array is the number of lines. This is necessary since
* Graphics.drawString(..) doesn't know about newline characters
*/
private String[] userMessage = new String[0];
/**
* Message that will appear in the middle of the screen in
* <code>LARGE_MESSAGE_FONT</code>.
*/
private String message = null;
/** Time at which to stop displaying the current user message. */
private long displayMessageUntil = 0;
private FreerailsCursor mapCursor;
/**
* Affects scroll direction and scroll speed relative to the cursor.
* Examples:
* <p>
* 1 := grab map, move 1:1
* <p>
* -2 := invert mouse, scroll twice as fast
*/
private final int LINEAR_ACCEL = -1;
/**
* Affects the granularity of the map scrolling (the map is scrolled in
* tileSize/GRANULARITY intervals). Multiply this value with LINEAR_ACCEL to
* be independent of acceleration.
*/
private final int GRANULARITY = 2 * LINEAR_ACCEL;
/**
* A {@link Robot} to compensate mouse cursor movement.
*/
private static Robot robot;
static {
try {
robot = new Robot();
} catch (java.awt.AWTException e) {
}
}
/**
* Implements a MouseListener for FreerailsCursor-movement (left mouse
* button) and a MouseMotionListener for map-scrolling (right mouse button).
* <p>
* Possible enhancements: setCursor(blankCursor),
* g.draw(cursorimage,lastMouseLocation.x,lastMouseLocation.y,null)
*/
final private class MapViewJComponentMouseAdapter extends MouseInputAdapter {
/**
* Screen location of the mouse cursor, when the second mouse button was
* pressed.
*/
private Point screenLocation = new Point();
private Point lastMouseLocation = new Point();
/**
* A variable to sum up relative mouse movement.
*/
private Point sigmadelta = new Point();
/**
* Where to scroll - Reflects granularity, scroll direction and
* acceleration, respects bounds.
*/
private Point tiledelta = new Point();
@Override
public void mousePressed(MouseEvent evt) {
/*
* Note, moving the cursor using the mouse is now handled in
* UserInputOnMapController
*/
if (SwingUtilities.isRightMouseButton(evt)) {
MapViewJComponentConcrete.this
.setCursor(Cursor
.getPredefinedCursor((LINEAR_ACCEL > 0) ? Cursor.HAND_CURSOR
: Cursor.MOVE_CURSOR));
lastMouseLocation.x = evt.getX();
lastMouseLocation.y = evt.getY();
screenLocation.x = evt.getX();
screenLocation.y = evt.getY();
sigmadelta.x = 0;
sigmadelta.y = 0;
javax.swing.SwingUtilities.convertPointToScreen(screenLocation,
MapViewJComponentConcrete.this);
}
}
@Override
public void mouseReleased(MouseEvent evt) {
MapViewJComponentConcrete.this.setCursor(Cursor
.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
@Override
public void mouseDragged(MouseEvent evt) {
if (SwingUtilities.isRightMouseButton(evt)) {
sigmadelta.x += evt.getX() - lastMouseLocation.x;
sigmadelta.y += evt.getY() - lastMouseLocation.y;
int tileSize = (int) getScale();
tiledelta.x = (sigmadelta.x * GRANULARITY) / tileSize;
tiledelta.y = (sigmadelta.y * GRANULARITY) / tileSize;
tiledelta.x = ((tiledelta.x * tileSize) / GRANULARITY)
* LINEAR_ACCEL;
tiledelta.y = ((tiledelta.y * tileSize) / GRANULARITY)
* LINEAR_ACCEL;
Rectangle vr = MapViewJComponentConcrete.this.getVisibleRect();
Rectangle bounds = MapViewJComponentConcrete.this.getBounds();
int temp; // respect bounds
if ((temp = vr.x - tiledelta.x) < 0) {
sigmadelta.x += temp / LINEAR_ACCEL;
tiledelta.x += temp;
} else if ((temp = (bounds.width) - (vr.x + vr.width)
+ tiledelta.x) < 0) {
sigmadelta.x -= temp / LINEAR_ACCEL;
tiledelta.x -= temp;
}
if ((temp = vr.y - tiledelta.y) < 0) {
sigmadelta.y += temp / LINEAR_ACCEL;
tiledelta.y += temp;
} else if ((temp = (bounds.height) - (vr.y + vr.height)
+ tiledelta.y) < 0) {
sigmadelta.y -= temp / LINEAR_ACCEL;
tiledelta.y -= temp;
}
if (tiledelta.x != 0 || tiledelta.y != 0) {
vr.x -= tiledelta.x;
vr.y -= tiledelta.y;
MapViewJComponentConcrete.this.scrollRectToVisible(vr);
sigmadelta.x -= tiledelta.x / LINEAR_ACCEL;
sigmadelta.y -= tiledelta.y / LINEAR_ACCEL;
lastMouseLocation.x -= tiledelta.x;
lastMouseLocation.y -= tiledelta.y;
}
MapViewJComponentConcrete.robot.mouseMove(screenLocation.x,
screenLocation.y);
}
}
}
@Override
protected void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
if (null != mapCursor && this.isFocusOwner()) {
mapCursor.paintCursor(g, new java.awt.Dimension(30, 30));
}
if (System.currentTimeMillis() < this.displayMessageUntil) {
Rectangle visRect = this.getVisibleRect();
g.setColor(Color.WHITE);
g.setFont(USER_MESSAGE_FONT);
for (int i = 0; i < userMessage.length; i++) {
g.drawString(this.userMessage[i], 50 + visRect.x, 50
+ visRect.y + i * 20);
}
}
if (message != null) {
Rectangle visRect = this.getVisibleRect();
g.setColor(Color.lightGray);
g.setFont(LARGE_MESSAGE_FONT);
int msgWidth = g.getFontMetrics(LARGE_MESSAGE_FONT).stringWidth(
message);
int msgHeight = g.getFontMetrics(LARGE_MESSAGE_FONT).getHeight();
g.drawString(message,
(int) (visRect.x + (visRect.getWidth() - msgWidth) / 2),
(int) (visRect.y + (visRect.getHeight() - msgHeight) / 2));
}
}
public MapViewJComponentConcrete() {
super();
MapViewJComponentMouseAdapter mva = new MapViewJComponentMouseAdapter();
this.addMouseListener(mva);
this.addMouseMotionListener(mva);
}
public void setup(MapRenderer mv, ModelRootImpl mr, RenderersRoot rr)
throws IOException {
super.setMapView(mv);
this.setBorder(null);
this.mapCursor = new FreerailsCursor(mr, rr);
mr.addPropertyChangeListener(this);
}
public void setup(MapRenderer mv) {
super.setMapView(mv);
}
private void react2cursorMove(ImPoint newPoint, ImPoint oldPoint) {
float scale = getMapView().getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
Rectangle vr = this.getVisibleRect();
Rectangle rectangleSurroundingCursor = new Rectangle(0, 0, 1, 1);
rectangleSurroundingCursor.setLocation((newPoint.x - 1)
* tileSize.width, (newPoint.y - 1) * tileSize.height);
rectangleSurroundingCursor.setSize(tileSize.width * 3,
tileSize.height * 3);
if (!(vr.contains(rectangleSurroundingCursor))) {
int x = newPoint.x * tileSize.width - vr.width / 2;
int y = newPoint.y * tileSize.height - vr.height / 2;
this.scrollRectToVisible(new Rectangle(x, y, vr.width, vr.height));
}
this.repaint((newPoint.x - 1) * tileSize.width, (newPoint.y - 1)
* tileSize.height, tileSize.width * 3, tileSize.height * 3);
this.repaint((oldPoint.x - 1) * tileSize.width, (oldPoint.y - 1)
* tileSize.height, tileSize.width * 3, tileSize.height * 3);
}
public void paintTile(Graphics g, int tileX, int tileY) {
throw new UnsupportedOperationException();
}
public void refreshTile(int x, int y) {
throw new UnsupportedOperationException();
}
public void refreshAll() {
this.getMapView().refreshAll();
}
public void paintRect(Graphics g, Rectangle visibleRect) {
throw new UnsupportedOperationException();
}
public FreerailsCursor getMapCursor() {
return mapCursor;
}
private void println(String s) {
StringTokenizer st = new StringTokenizer(s, "\n");
this.userMessage = new String[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
userMessage[i] = st.nextToken();
i++;
}
// Display the message for 5 seconds.
displayMessageUntil = System.currentTimeMillis() + 1000 * 5;
}
/**
* Checks what triggered the specified PropertyChangeEvent and reacts as
* follows.
* <p>
* (1) If it was ModelRoot.CURSOR_POSITION, scrolls the map if necessary.
* </p>
* <p>
* (2) If it was ModelRoot.QUICK_MESSAGE, display or hide the message as
* appropriate.
* </p>
* <p>
* (3) If it was ModelRoot.PERMANENT_MESSAGE, display or hide the message as
* appropriate.
* </p>
*/
public void propertyChange(ModelRoot.Property p, Object before, Object after) {
if (p.equals(ModelRoot.Property.CURSOR_POSITION)) {
ImPoint newPoint = (ImPoint) after;
ImPoint oldPoint = (ImPoint) before;
if (null == oldPoint) {
oldPoint = new ImPoint();
}
react2cursorMove(newPoint, oldPoint);
} else if (p.equals(ModelRoot.Property.QUICK_MESSAGE)) {
String newMessage = (String) after;
if (null != newMessage) {
println(newMessage);
} else {
// Its null, so stop displaying whatever we where displaying.
displayMessageUntil = Long.MIN_VALUE;
}
} else if (p.equals(ModelRoot.Property.PERMANENT_MESSAGE)) {
message = (String) after;
}
}
}
Methods:
MethodJavadoc
getMapCursor
paintComponent
paintRect
paintTile
println
propertyChange/**
react2cursorMove
refreshAll
refreshTile
setup
setup
jfreerails.client.view.NearestStationFinder
Javadoc:
/** * Provides methods that find the nearest station in a given direction, used by * the select station popup window. * * @author Luke * */
Source code:
/**
* Provides methods that find the nearest station in a given direction, used by
* the select station popup window.
*
* @author Luke
*
*/
public class NearestStationFinder {
public static final int NOT_FOUND = Integer.MIN_VALUE;
private final ReadOnlyWorld world;
private final FreerailsPrincipal principal;
private final int MAX_DISTANCE_TO_SELECT_SQUARED = 20 * 20;
public NearestStationFinder(ReadOnlyWorld w, FreerailsPrincipal player) {
world = w;
this.principal = player;
}
public int findNearestStation(int x, int y) {
// Find nearest station.
int distanceToClosestSquared = Integer.MAX_VALUE;
NonNullElements it = new NonNullElements(KEY.STATIONS, world, principal);
int nearestStation = NOT_FOUND;
while (it.next()) {
StationModel station = (StationModel) it.getElement();
int deltaX = x - station.x;
int deltaY = y - station.y;
int distanceSquared = deltaX * deltaX + deltaY * deltaY;
if (distanceSquared < distanceToClosestSquared
&& MAX_DISTANCE_TO_SELECT_SQUARED > distanceSquared) {
distanceToClosestSquared = distanceSquared;
nearestStation = it.getIndex();
}
}
return nearestStation;
}
public int findNearestStationInDirection(int startStation, Step direction) {
int distanceToClosestSquared = Integer.MAX_VALUE;
NonNullElements it = new NonNullElements(KEY.STATIONS, world, principal);
StationModel currentStation = (StationModel) world.get(principal,
KEY.STATIONS, startStation);
int nearestStation = NOT_FOUND;
while (it.next()) {
StationModel station = (StationModel) it.getElement();
int deltaX = station.x - currentStation.x;
int deltaY = station.y - currentStation.y;
int distanceSquared = deltaX * deltaX + deltaY * deltaY;
boolean closer = distanceSquared < distanceToClosestSquared;
boolean notTheSameStation = startStation != it.getIndex();
boolean inRightDirection = isInRightDirection(direction, deltaX,
deltaY);
if (closer && inRightDirection && notTheSameStation) {
distanceToClosestSquared = distanceSquared;
nearestStation = it.getIndex();
}
}
return nearestStation;
}
/**
* Returns true if the angle between direction and the vector (deltaX,
* deltaY) is less than 45 degrees.
*/
private boolean isInRightDirection(Step direction, int deltaX, int deltaY) {
boolean isDiagonal = direction.deltaX * direction.deltaY != 0;
boolean sameXDirection = (direction.deltaX * deltaX) > 0;
boolean sameYDirection = (direction.deltaY * deltaY > 0);
boolean deltaXisLongerThanDeltaY = deltaX * deltaX < deltaY * deltaY;
if (isDiagonal) {
return sameXDirection && sameYDirection;
}
if (0 == direction.deltaX) {
return deltaXisLongerThanDeltaY && sameYDirection;
}
return !deltaXisLongerThanDeltaY && sameXDirection;
}
}
Methods:
MethodJavadoc
findNearestStation
findNearestStationInDirection
isInRightDirection/**
jfreerails.client.view.NetWorthGraphJPanel
Javadoc:
/** * A JPanel that displays a graph of the net worth of each of the players * against time. * * @author Luke * */
Source code:
/**
* A JPanel that displays a graph of the net worth of each of the players
* against time.
*
* @author Luke
*
*/
public class NetWorthGraphJPanel extends JPanel implements View {
private static final long serialVersionUID = 3618703010813980982L;
private static final Logger logger = Logger
.getLogger(NetWorthGraphJPanel.class.getName());
private JLabel title = null;
private JLabel yAxisLabel1 = null;
private JLabel yAxisLabel3 = null;
private JLabel yAxisLabel4 = null;
private JLabel yAxisLabel2 = null;
private JLabel xAxisLabel3 = null;
private JLabel xAxisLabel2 = null;
private JLabel xAxisLabel1 = null;
private final Font FONT;
private ArrayList<CompanyDetails> companies = new ArrayList<CompanyDetails>();
private long scaleMax;
private Rectangle graphRect = new Rectangle(44, 50, 380, 245);
ActionListener submitButtonCallBack = null;
/**
* Stores the company details that are used to draw a line and title on the
* graph.
*
* @author Luke
*
*/
static class CompanyDetails {
/** The company's net worth at the end of each year. */
long[] value = new long[100];
/** The colour for the line on the graph. */
final Color color;
/** The company's name. */
final String name;
CompanyDetails(String n, Color c) {
color = c;
name = n;
for (int i = 0; i < 100; i++) {
value[i] = Integer.MIN_VALUE;
}
}
}
/**
* This method initializes
*
*/
public NetWorthGraphJPanel() {
super();
FONT = new java.awt.Font("Bookman Old Style", java.awt.Font.BOLD, 10);
initialize();
// companies.add(new CompanyDetails("Player 1", Color.BLUE));
// companies.add(new CompanyDetails("Player 2", Color.GREEN));
// companies.add(new CompanyDetails("Player 3", Color.CYAN));
// for(int i = 0; i < companies.size(); i++){
// CompanyDetails cd = (CompanyDetails)companies.get(i);
// cd.fillWithRnadomData();
// }
//
// setAppropriateScale();
}
/**
* This method initializes this
*
*/
private void initialize() {
yAxisLabel4 = new JLabel();
yAxisLabel3 = new JLabel();
yAxisLabel2 = new JLabel();
xAxisLabel1 = new JLabel();
xAxisLabel2 = new JLabel();
xAxisLabel3 = new JLabel();
title = new JLabel();
yAxisLabel1 = new JLabel();
this.setLayout(null);
this.setBackground(java.awt.Color.white);
this.setSize(444, 315);
title.setText("Net Worth");
title.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.PLAIN, 24));
title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
title.setLocation(0, 0);
title.setSize(444, 43);
yAxisLabel1.setText("$25");
yAxisLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
yAxisLabel3.setText("$999m");
yAxisLabel4.setText("$999M");
yAxisLabel4.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
yAxisLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
yAxisLabel3.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
yAxisLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
yAxisLabel2.setText("$50");
yAxisLabel2.setLocation(0, 167);
yAxisLabel2.setSize(40, 16);
yAxisLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
yAxisLabel2.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
yAxisLabel1.setLocation(0, 227);
yAxisLabel1.setSize(40, 16);
yAxisLabel3.setLocation(0, 107);
yAxisLabel3.setSize(40, 16);
yAxisLabel4.setLocation(0, 47);
yAxisLabel4.setSize(40, 16);
xAxisLabel3.setText("2000");
xAxisLabel3.setLocation(400, 300);
xAxisLabel3.setSize(40, 17);
xAxisLabel3.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
xAxisLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
xAxisLabel2.setText("1950");
xAxisLabel2.setLocation(210, 300);
xAxisLabel2.setSize(40, 17);
xAxisLabel2.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
xAxisLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
xAxisLabel1.setText("1900");
xAxisLabel1.setLocation(20, 300);
xAxisLabel1.setSize(40, 17);
xAxisLabel1.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
xAxisLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
this.add(xAxisLabel3, null);
this.add(xAxisLabel2, null);
this.add(xAxisLabel1, null);
yAxisLabel1.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
this.add(title, null);
this.add(yAxisLabel1, null);
this.add(yAxisLabel3, null);
this.add(yAxisLabel2, null);
this.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
if (null == submitButtonCallBack) {
System.err.println("mouseClicked");
} else {
submitButtonCallBack.actionPerformed(new ActionEvent(this,
0, null));
}
}
});
this.add(yAxisLabel4, null);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(2f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL));
// Draw guide lines.
g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL));
g.setColor(Color.GRAY);
for (int y = 295; y > 50; y -= 60) {
g2.drawLine(graphRect.x, y, 420, y);
}
g2.setStroke(new BasicStroke(2f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL));
// Draw key
for (int i = 0; i < companies.size(); i++) {
int yOffset = i * 20;
CompanyDetails company = companies.get(i);
g2.setColor(company.color);
g2.drawLine(50, 70 + yOffset, 60, 70 + yOffset);
g2.setColor(Color.BLACK);
g2.setFont(FONT);
g.drawString(company.name, 65, 72 + yOffset);
}
// Draw graphs lines
for (int i = 0; i < companies.size(); i++) {
CompanyDetails company = companies.get(i);
g2.setColor(company.color);
for (int year = 1; year < 100; year++) {
if (company.value[year] != Integer.MIN_VALUE
&& company.value[year - 1] != Integer.MIN_VALUE) {
long x1 = year * graphRect.width / 100 + graphRect.x;
long y1 = company.value[year] * graphRect.height / scaleMax;
y1 = Math.max(1, y1);
y1 = graphRect.y + graphRect.height - y1;
long x2 = (year - 1) * graphRect.width / 100 + graphRect.x;
long y2 = company.value[year - 1] * graphRect.height
/ scaleMax;
y2 = Math.max(1, y2);
y2 = graphRect.y + graphRect.height - y2;
g2.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
}
}
}
// Draw axis
g2.setColor(Color.BLACK);
g2.drawLine(graphRect.x, graphRect.y, graphRect.x, graphRect.y
+ graphRect.height);
g2.drawLine(graphRect.x, graphRect.y + graphRect.height, graphRect.x
+ graphRect.width, graphRect.y + graphRect.height);
}
/**
* <p>
* Sets the value of scaleMax subject to the following constraints.
* </P>
* <p>
* (1) scaleMax >= max, where max is the max net worth value.
* </p>
* <p>
* (2) (scaleMax % 4) == 0
* </p>
* <p>
* (3) if max >= 1,000, then (scaleMax % 4,000) == 0
* </p>
* <p>
* (4) if max >= 1,000,000, then (scaleMax % 4,000,000) == 0
* </p>
* <p>
* (5) if max >= 1,000,000,000, then (scaleMax % 4,000,000,000) == 0
* </p>
*/
private void setAppropriateScale() {
long max = 0;
for (int i = 0; i < companies.size(); i++) {
CompanyDetails company = companies.get(i);
for (int year = 0; year < 100; year++) {
long value = company.value[year];
if (value > max) {
max = value;
}
}
}
long increment = 1;
while (scaleMax < max) {
scaleMax = increment;
if (scaleMax < max) {
scaleMax += increment;
int loopCount = 0;
while (scaleMax < max && loopCount < 3) {
scaleMax += increment * 2;
loopCount++;
}
}
increment = increment * 10;
}
/*
* Make sure that if the scale is in k/m/b that each of the quarter
* scales will be divisible by k/m/b.
*/
increment = 1;
for (int i = 0; i < 3; i++) {
increment = increment * 1000;
if (scaleMax >= 8 * increment && scaleMax < 12 * increment) {
scaleMax = 12 * increment;
} else if (scaleMax >= 4 * increment && scaleMax < 8 * increment) {
scaleMax = 8 * increment;
} else if (scaleMax >= 1 * increment && scaleMax < 4 * increment) {
scaleMax = 4 * increment;
}
}
if (scaleMax < 100) {
scaleMax = 100;
}
long quarterScale = scaleMax / 4;
yAxisLabel1.setText(getYScaleString(quarterScale));
yAxisLabel2.setText(getYScaleString(quarterScale * 2));
yAxisLabel3.setText(getYScaleString(quarterScale * 3));
yAxisLabel4.setText(getYScaleString(quarterScale * 4));
}
private String getYScaleString(long value) {
String abv;
if (value >= 1000000000) {
value = value / 1000000000;
abv = "b";
} else if (value >= 1000000) {
value = value / 1000000;
abv = "m";
} else if (value >= 1000) {
value = value / 1000;
abv = "k";
} else {
abv = "";
}
return "$" + String.valueOf(value) + abv;
}
public void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
this.submitButtonCallBack = closeAction;
ReadOnlyWorld world = modelRoot.getWorld();
companies = new ArrayList<CompanyDetails>();
GameCalendar calender = (GameCalendar) world.get(ITEM.CALENDAR);
int startYear = calender.getYear(0);
int endYear = startYear + 100;
GameTime currentTime = world.currentTime();
int currentYear = calender.getYear(currentTime.getTicks());
xAxisLabel1.setText(String.valueOf(startYear));
xAxisLabel2.setText(String.valueOf(startYear + 50));
xAxisLabel3.setText(String.valueOf(endYear));
for (int i = 0; i < world.getNumberOfPlayers(); i++) {
Color c = PlayerColors.getColor(i);
Player player = world.getPlayer(i);
String name = player.getName();
logger.fine("Adding player " + name + " to net worth graph.");
CompanyDetails cd = new CompanyDetails(name, c);
GameTime[] times = new GameTime[101];
for (int year = 0; year < 101; year++) {
int ticks = calender.getTicks(startYear + year - 1);
times[year] = new GameTime(ticks);
}
TransactionAggregator aggregator = new NetWorthCalculator(world,
player.getPrincipal());
aggregator.setTimes(times);
Money[] values = aggregator.calculateValues();
int stopYear = currentYear - startYear + 1;
for (int year = 0; year < stopYear; year++) {
cd.value[year] = values[year].getAmount();
}
companies.add(cd);
}
setAppropriateScale();
}
} // @jve:decl-index=0:visual-constraint="10,10"
Methods:
MethodJavadoc
getYScaleString
initialize/**
paintComponent
setAppropriateScale/**
setup
jfreerails.client.view.NewsPaperJPanel
Javadoc:
/** * A JPanel that displays a newspaper headline. * * @author lindsal8 * */
Source code:
/**
* A JPanel that displays a newspaper headline.
*
* @author lindsal8
*
*/
public class NewsPaperJPanel extends javax.swing.JPanel implements View {
private static final long serialVersionUID = 3258410638366946868L;
private final GraphicsConfiguration defaultConfiguration = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
private ActionListener callBack;
private final Image pieceOfNewspaper;
public NewsPaperJPanel() {
initComponents();
Image tempImage = (new javax.swing.ImageIcon(getClass().getResource(
"/jfreerails/data/newspaper.png"))).getImage();
pieceOfNewspaper = defaultConfiguration.createCompatibleImage(tempImage
.getWidth(null), tempImage.getHeight(null),
Transparency.BITMASK);
Graphics g = pieceOfNewspaper.getGraphics();
g.drawImage(tempImage, 0, 0, null);
this.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mousePressed(java.awt.event.MouseEvent evt) {
callBack.actionPerformed(new ActionEvent(this, 0, null));
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() { // GEN-BEGIN:initComponents
headline = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
anyKeyToContinueJLabel = new javax.swing.JLabel();
setLayout(null);
setPreferredSize(new java.awt.Dimension(640, 400));
setMinimumSize(new java.awt.Dimension(640, 400));
setMaximumSize(new java.awt.Dimension(640, 400));
setOpaque(false);
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
headline.setPreferredSize(new java.awt.Dimension(620, 110));
headline.setMinimumSize(new java.awt.Dimension(620, 110));
headline.setText("NEWSPAPER HEADLINE");
headline.setForeground(java.awt.Color.black);
headline.setBackground(java.awt.Color.white);
headline.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
headline.setFont(new java.awt.Font("Lucida Bright", 1, 36));
headline.setMaximumSize(new java.awt.Dimension(620, 110));
add(headline);
headline.setBounds(10, 70, 620, 110);
jPanel1.setBorder(new javax.swing.border.BevelBorder(0));
anyKeyToContinueJLabel.setText("Click to continue");
anyKeyToContinueJLabel.setForeground(java.awt.Color.black);
anyKeyToContinueJLabel.setBackground(java.awt.Color.darkGray);
jPanel1.add(anyKeyToContinueJLabel);
add(jPanel1);
jPanel1.setBounds(230, 260, 190, 30);
}
// GEN-END:initComponents
private void formKeyPressed(java.awt.event.KeyEvent evt) { // GEN-FIRST:event_formKeyPressed
// Add your handling code here:
this.setVerifyInputWhenFocusTarget(false);
}
// GEN-LAST:event_formKeyPressed
@Override
public void paint(Graphics g) {
g.drawImage(this.pieceOfNewspaper, 0, 0, null);
this.paintChildren(g);
}
public void setHeadline(String s) {
this.headline.setText(s);
}
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
this.callBack = closeAction;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel headline;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel anyKeyToContinueJLabel;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
formKeyPressed
initComponents/**
paint
setHeadline
setup
jfreerails.client.view.OverHeadTrainView
Javadoc:
/** * Draws the trains on the main map. * * @author Luke */
Source code:
/**
* Draws the trains on the main map.
*
* @author Luke
*/
public class OverHeadTrainView implements Painter {
private final TrainRenderer trainRenderer;
private final ReadOnlyWorld w;
private SoundManager soundManager = SoundManager.getSoundManager();
private ModelRoot mr;
public OverHeadTrainView(ReadOnlyWorld world, RenderersRoot rr, ModelRoot mr) {
this.w = world;
trainRenderer = new TrainRenderer(rr);
this.mr = mr;
}
public TrainRenderer getTrainRenderer() {
return trainRenderer;
}
public void paint(Graphics2D g) {
g.setColor(Color.BLUE);
g.setStroke(new BasicStroke(10));
Double time = (Double)mr.getProperty(Property.TIME);
for (int k = 0; k < w.getNumberOfPlayers(); k++) {
FreerailsPrincipal principal = w.getPlayer(k).getPrincipal();
int selectedTrain = -1;
if (mr.getPrincipal().getWorldIndex() == principal.getWorldIndex()) {
//These are our trains...
Object property = mr.getProperty(Property.SELECTED_TRAIN);
if (null != property) {
selectedTrain = (Integer) property;
}
}
for (int i = 0; i < w.size(principal, KEY.TRAINS); i++) {
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS, i);
// TrainPositionOnMap pos = (TrainPositionOnMap) w.get(
// principal, KEY.TRAIN_POSITIONS, i);
TrainAccessor ta = new TrainAccessor(w, principal, i);
TrainPositionOnMap pos = ta.findPosition(time);
if (pos.isCrashSite()
&& (pos.getFrameCt() <= TrainPositionOnMap.CRASH_FRAMES_COUNT)) {
trainRenderer.paintTrainCrash(g, pos);
if (pos.getFrameCt() == 1) {
try {
soundManager.playSound(
"/jfreerails/client/sounds/traincrash.wav",
1);
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
TrainImages.Highlight highlight = i == selectedTrain ? TrainImages.Highlight.SELECTED: null;
trainRenderer.paintTrain(g, train, pos, highlight);
}
}
}
}
}
Methods:
MethodJavadoc
getTrainRenderer
paint
jfreerails.client.view.OverviewMapJComponent
Javadoc:
/** * JPanel that displays the overview map and a rectangle showing the region of * the map currently displayed on the main view. * * @author Luke */
Source code:
/**
* JPanel that displays the overview map and a rectangle showing the region of
* the map currently displayed on the main view.
*
* @author Luke
*/
public class OverviewMapJComponent extends JPanel {
private static final long serialVersionUID = 3258697585148376888L;
private MapRenderer mapView = new BlankMapRenderer(0.4F);
private final Rectangle mainMapVisRect;
public OverviewMapJComponent(Rectangle r) {
this.setPreferredSize(mapView.getMapSizeInPixels());
mainMapVisRect = r;
}
public void setup(MapRenderer mv) {
mapView = mv;
this.setPreferredSize(mapView.getMapSizeInPixels());
this.setMinimumSize(this.getPreferredSize());
this.setSize(this.getPreferredSize());
if (null != this.getParent()) {
this.getParent().validate();
}
}
@Override
protected void paintComponent(java.awt.Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
java.awt.Rectangle r = this.getVisibleRect();
mapView.paintRect(g2, r);
g2.setColor(Color.WHITE);
g2.drawRect(mainMapVisRect.x, mainMapVisRect.y, mainMapVisRect.width,
mainMapVisRect.height);
}
@Override
public Dimension getPreferredSize() {
return mapView.getMapSizeInPixels();
}
}
Methods:
MethodJavadoc
getPreferredSize
paintComponent
setup
jfreerails.client.view.PlayerColors
Javadoc:
/** * Stores a list of colours to use to represent different players. * * @author Luke * */
Source code:
/**
* Stores a list of colours to use to represent different players.
*
* @author Luke
*
*/
public class PlayerColors {
private static final Color[] colors = new Color[] { Color.BLUE,
Color.GREEN, Color.CYAN, Color.MAGENTA, Color.ORANGE, Color.YELLOW };// Save
// red
// for
// when
// we
// need
// to
// grab
// the
// player's
// attention!
public static Color getColor(int playerNumber) {
return colors[playerNumber % colors.length];
}
}
Methods:
MethodJavadoc
getColor
jfreerails.client.view.RHSJTabPane
Javadoc:
/** * The tabbed panel that sits in the lower right hand corner of the screen. * * @author rob */
Source code:
/**
* The tabbed panel that sits in the lower right hand corner of the screen.
*
* @author rob
*/
public class RHSJTabPane extends JTabbedPane implements ModelRootListener {
private static final long serialVersionUID = 3906926798502965297L;
private final TerrainInfoJPanel terrainInfoPanel;
private final StationInfoJPanel stationInfoPanel;
private final TrainListJPanel trainListPanel;
private final BuildTrackJPanel buildTrackPanel;
private ReadOnlyWorld world;
private int trainListIndex;
public RHSJTabPane() {
/*
* Dont accept keyboard focus since we want to leave it with the main
* map view.
*/
setFocusable(false);
ImageIcon trainListIcon;
ImageIcon buildTrackIcon;
/* set up trainsJTabbedPane */
setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
terrainInfoPanel = new TerrainInfoJPanel();
trainListPanel = new TrainListJPanel(true);
buildTrackPanel = new BuildTrackJPanel();
trainListPanel.removeButtons();
URL terrainInfoIconUrl = getClass().getResource(
"/jfreerails/client/graphics/icons/terrain_info.png");
ImageIcon terrainInfoIcon = new ImageIcon(terrainInfoIconUrl);
URL buildTrackIconUrl = getClass().getResource(
"/jfreerails/client/graphics/icons/track_new.png");
buildTrackIcon = new ImageIcon(buildTrackIconUrl);
URL trainListIconUrl = getClass().getResource(
"/jfreerails/client/graphics/icons/train_list.png");
trainListIcon = new ImageIcon(trainListIconUrl);
// Note titles set to null so only the icon appears at the top of the
// top.
JScrollPane terrainInfoJScrollPane = new JScrollPane(terrainInfoPanel);
terrainInfoJScrollPane
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
addTab(null, terrainInfoIcon, terrainInfoJScrollPane, "Terrain Info");
stationInfoPanel = new StationInfoJPanel();
stationInfoPanel.removeCloseButton();
// Don't show the station info tab until it has been rewritten to take
// up less space.
// JScrollPane stationInfoJScrollPane = new
// JScrollPane(stationInfoPanel);
// stationInfoJScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
// addTab(null, stationInfoIcon, stationInfoJScrollPane, "Station
// Info");
// this.stationInfoIndex= this.getTabCount()-1;
trainListPanel.setTrainViewHeight(20);
addTab(null, buildTrackIcon, buildTrackPanel, "Build Track");
addTab(null, trainListIcon, trainListPanel, "Train List");
this.trainListIndex = this.getTabCount() - 1;
/* These values were picked by trial and error! */
this.setMinimumSize(new Dimension(250, 200));
}
public void setup(final ActionRoot actionRoot, RenderersRoot vl,
final ModelRootImpl modelRoot) {
world = modelRoot.getWorld();
terrainInfoPanel.setup(world, vl);
stationInfoPanel.setup(modelRoot, vl, null);
ActionListener showTrain = new ActionListener() {
public void actionPerformed(ActionEvent e) {
int id = trainListPanel.getSelectedTrainID();
actionRoot.getDialogueBoxController().showTrainOrders(id);
}
};
trainListPanel.setShowTrainDetailsActionListener(showTrain);
trainListPanel.setup(modelRoot, vl, null);
modelRoot.addPropertyChangeListener(this);
buildTrackPanel.setup(modelRoot, actionRoot, vl, null);
}
/**
* Updates the Terrain Info Panel if the specified PropertyChangeEvent was
* triggered by the cursor moving.
*/
public void propertyChange(ModelRoot.Property prop, Object before,
Object after) {
if (prop.equals(ModelRoot.Property.CURSOR_POSITION)) {
ImPoint p = (ImPoint) after;
terrainInfoPanel.setTerrainType(((FreerailsTile) world.getTile(p.x,
p.y)).getTerrainTypeID());
}
}
public void setTrainTabEnabled(boolean enabled) {
this.setEnabledAt(this.trainListIndex, enabled);
}
public void setStationTabEnabled(boolean enabled) {
// this.setEnabledAt(this.stationInfoIndex, enabled);
}
}
Methods:
MethodJavadoc
propertyChange/**
setStationTabEnabled
setTrainTabEnabled
setup
jfreerails.client.view.SaveGameJPanel
Javadoc:
/** * * @author Luke */
Source code:
/**
*
* @author Luke
*/
public class SaveGameJPanel extends javax.swing.JPanel implements View{
private static final long serialVersionUID = 4031907071040752589L;
/** Creates new form SaveGameJPanel */
public SaveGameJPanel() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jLabel1 = new javax.swing.JLabel();
fileNameTextField = new javax.swing.JTextField();
oKButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
jLabel1.setText("Please enter a name for the save game.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(jLabel1, gridBagConstraints);
fileNameTextField.setText("savegame");
fileNameTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileNameTextFieldActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(fileNameTextField, gridBagConstraints);
oKButton.setText("OK");
oKButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
oKButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(oKButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(cancelButton, gridBagConstraints);
}
// </editor-fold>//GEN-END:initComponents
private void oKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_oKButtonActionPerformed
String filename = fileNameTextField.getText();
// Save the current game using the string
modelRoot.setProperty(Property.QUICK_MESSAGE, "Saved game "
+ filename);
Message2Server message2 = new SaveGameMessage2Server(1,
filename + ".sav");
modelRoot.sendCommand(message2);
close.actionPerformed(evt);
}//GEN-LAST:event_oKButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
close.actionPerformed(evt);
}//GEN-LAST:event_cancelButtonActionPerformed
private void fileNameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileNameTextFieldActionPerformed
// TODO add your handling code here:
System.out.println("fileNameTextFieldActionPerformed"+evt.toString());
}//GEN-LAST:event_fileNameTextFieldActionPerformed
public void setup(ModelRoot m, RenderersRoot vl,
Action closeAction) {
this.close = closeAction;
this.modelRoot = m;
}
ModelRoot modelRoot;
ActionListener close;
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JButton cancelButton;
javax.swing.JTextField fileNameTextField;
javax.swing.JLabel jLabel1;
javax.swing.JButton oKButton;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
cancelButtonActionPerformed
fileNameTextFieldActionPerformed
initComponents/** This method is called from within the constructor to
oKButtonActionPerformed/**
setup
jfreerails.client.view.SelectEngineJPanel
Javadoc:
/** * This JPanel lets the user select an engine from a list. * * @author lindsal8 * */
Source code:
/**
* This JPanel lets the user select an engine from a list.
*
* @author lindsal8
*
*/
public class SelectEngineJPanel extends javax.swing.JPanel implements View {
private static final long serialVersionUID = 4122537730158179638L;
public SelectEngineJPanel() {
initComponents();
jList1ValueChanged(null); // Disable the ok button if no engine type
// is selected.
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
okjButton = new javax.swing.JButton();
canceljButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(400, 350));
okjButton.setText("OK");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 9, 10);
add(okjButton, gridBagConstraints);
canceljButton.setText("Cancel");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
add(canceljButton, gridBagConstraints);
jList1
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1
.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(
javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jScrollPane1.setViewportView(jList1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}// GEN-END:initComponents
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) { // GEN-FIRST:event_jList1ValueChanged
// We need to disable the OK button if no engine type is selected.
if (-1 == jList1.getSelectedIndex()) {
okjButton.setEnabled(false);
} else {
okjButton.setEnabled(true);
}
} // GEN-LAST:event_jList1ValueChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton canceljButton;
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton okjButton;
// End of variables declaration//GEN-END:variables
final private class TrainCellRenderer implements ListCellRenderer {
final JLabel label;
final RenderersRoot rr;
public TrainCellRenderer(RenderersRoot vl) {
rr = vl;
label = new JLabel();
}
public Component getListCellRendererComponent(JList list, Object value,
/* value to display */
int index, /* cell index */
boolean isSelected, /* is the cell selected */
boolean cellHasFocus) /* the list and the cell have the focus */{
EngineType engine = (EngineType) value;
label.setFont(new java.awt.Font("Dialog", 0, 12));
String text = "<html><body>" + (isSelected ? "<strong>" : "")
+ engine.getEngineTypeName() + "<br>"
+ engine.getMaxSpeed() + " m.p.h. "
+ engine.getPowerAtDrawbar() + " hp $"
+ engine.getPrice().toString()
+ (isSelected ? "</strong>" : "") + "</body></html>";
label.setText(text);
Image image = rr.getEngineImages(index).getSideOnImage();
int height = image.getHeight(null);
int width = image.getWidth(null);
int scale = height / 50;
ImageIcon icon = new ImageIcon(image.getScaledInstance(width
/ scale, height / scale, Image.SCALE_FAST));
label.setIcon(icon);
return label;
}
}
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
jList1.setModel(new World2ListModelAdapter(mr.getWorld(),
SKEY.ENGINE_TYPES));
jList1.setCellRenderer(new TrainCellRenderer(vl));
okjButton.addActionListener(closeAction);
}
/**
* Removes any existing ActionListener listeners from the cancel button,
* then adds the specified one.
*/
void setCancelButtonActionListener(ActionListener l) {
ActionListener[] oldListeners = canceljButton.getActionListeners();
for (int i = 0; i < oldListeners.length; i++) {
canceljButton.removeActionListener(oldListeners[i]);
}
this.canceljButton.addActionListener(l);
}
/**
* Returns the number of the currently selected engine type.
*
*/
public int getEngineType() {
return jList1.getSelectedIndex();
}
}
Methods:
MethodJavadoc
getEngineType/**
initComponents/**
jList1ValueChanged
setCancelButtonActionListener/**
setup
jfreerails.client.view.SelectStationJPanel
Javadoc:
/** * This JPanel lets the user select a station from a map and add it to a train * schedule. * * @author Luke */
Source code:
/**
* This JPanel lets the user select a station from a map and add it to a train
* schedule.
*
* @author Luke
*/
public class SelectStationJPanel extends javax.swing.JPanel implements View {
private static final long serialVersionUID = 3258411750662877488L;
private ReadOnlyWorld world;
private ActionListener submitButtonCallBack;
private int selectedStationID = 0;
private int selectedOrderNumber = 1;
private MutableSchedule schedule;
private Rectangle mapRect = new Rectangle();
private Rectangle visibleMapTiles = new Rectangle();
private double scale = 1;
private boolean needsUpdating = true;
private FreerailsPrincipal principal;
public SelectStationJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
cargoWaitingAndDemandedJPanel1 = new jfreerails.client.view.CargoWaitingAndDemandedJPanel();
jLabel1 = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(500, 350));
addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
@Override
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
formMouseClicked(evt);
}
});
addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
@Override
public void mouseMoved(java.awt.event.MouseEvent evt) {
formMouseMoved(evt);
}
});
cargoWaitingAndDemandedJPanel1
.setBorder(new javax.swing.border.LineBorder(
new java.awt.Color(0, 0, 0)));
cargoWaitingAndDemandedJPanel1.setPreferredSize(new java.awt.Dimension(
165, 300));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(cargoWaitingAndDemandedJPanel1, gridBagConstraints);
jLabel1.setText("Train #1 Stop 1");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
add(jLabel1, gridBagConstraints);
}// GEN-END:initComponents
private void formComponentShown(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_formComponentShown
setZoom();
}// GEN-LAST:event_formComponentShown
private void formMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_formMouseClicked
formMouseMoved(evt);
needsUpdating = true;
this.submitButtonCallBack.actionPerformed(null);
}// GEN-LAST:event_formMouseClicked
private void formKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_formKeyPressed
try {
Step v = KeyCode2OneTileMoveVector.getInstanceMappedToKey(evt
.getKeyCode());
// now find nearest station in direction of the vector.
NearestStationFinder stationFinder = new NearestStationFinder(
this.world, this.principal);
int station = stationFinder.findNearestStationInDirection(
this.selectedStationID, v);
if (selectedStationID != station
&& station != NearestStationFinder.NOT_FOUND) {
selectedStationID = station;
cargoWaitingAndDemandedJPanel1.display(selectedStationID);
this.validate();
this.repaint();
}
} catch (NoSuchElementException e) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
needsUpdating = true;
submitButtonCallBack.actionPerformed(null);
}
// The key pressed isn't mapped to a OneTileMoveVector so do
// nothing.
}
}// GEN-LAST:event_formKeyPressed
private void formComponentResized(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_formComponentResized
setZoom();
}// GEN-LAST:event_formComponentResized
private void formMouseMoved(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_formMouseMoved
// Add your handling code here:
double x = evt.getX();
x = x / scale + visibleMapTiles.x;
double y = evt.getY();
y = y / scale + visibleMapTiles.y;
NearestStationFinder stationFinder = new NearestStationFinder(
this.world, this.principal);
int station = stationFinder.findNearestStation((int) x, (int) y);
if (selectedStationID != station
&& station != NearestStationFinder.NOT_FOUND) {
selectedStationID = station;
cargoWaitingAndDemandedJPanel1.display(selectedStationID);
this.validate();
this.repaint();
}
}// GEN-LAST:event_formMouseMoved
public void display(MutableSchedule newSchedule, int orderNumber) {
this.schedule = newSchedule;
this.selectedOrderNumber = orderNumber;
TrainOrdersModel order = newSchedule.getOrder(selectedOrderNumber);
this.selectedStationID = order.getStationID();
// Set the text on the title JLabel.
this.jLabel1.setText("Stop " + String.valueOf(selectedOrderNumber + 1));
// Set the station info panel to show the current selected station.
cargoWaitingAndDemandedJPanel1.display(selectedStationID);
}
/**
* Sets the zoom based on the size of the component and the positions of the
* stations.
*/
private void setZoom() {
mapRect = this.getBounds();
Rectangle r = cargoWaitingAndDemandedJPanel1.getBounds();
mapRect.width -= r.width;
int topLeftX = Integer.MAX_VALUE;
int topLeftY = Integer.MAX_VALUE;
int bottomRightX = Integer.MIN_VALUE;
int bottomRightY = Integer.MIN_VALUE;
NonNullElements it = new NonNullElements(KEY.STATIONS, world,
this.principal);
while (it.next()) {
StationModel station = (StationModel) it.getElement();
if (station.x < topLeftX)
topLeftX = station.x;
if (station.y < topLeftY)
topLeftY = station.y;
if (station.x > bottomRightX)
bottomRightX = station.x;
if (station.y > bottomRightY)
bottomRightY = station.y;
}
// Add some padding.
topLeftX -= 10;
topLeftY -= 10;
bottomRightX += 10;
bottomRightY += 10;
int width = bottomRightX - topLeftX;
int height = bottomRightY - topLeftY;
visibleMapTiles = new Rectangle(topLeftX, topLeftY, width, height);
boolean heightConstraintBinds = (visibleMapTiles.getHeight() / visibleMapTiles
.getWidth()) > (mapRect.getHeight() / mapRect.getWidth());
if (heightConstraintBinds) {
scale = mapRect.getHeight() / visibleMapTiles.getHeight();
} else {
scale = mapRect.getWidth() / visibleMapTiles.getWidth();
}
needsUpdating = false;
}
@Override
protected void paintComponent(Graphics g) {
if (needsUpdating) {
this.setZoom();
}
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
NonNullElements it = new NonNullElements(KEY.STATIONS, world,
this.principal);
// Draw track
g2.setColor(Color.BLACK);
for (int x = Math.max(0, visibleMapTiles.x); x < Math.min(
visibleMapTiles.width + visibleMapTiles.x, world.getMapWidth()); x++) {
for (int y = Math.max(0, visibleMapTiles.y); y < Math.min(
visibleMapTiles.height + visibleMapTiles.y, world
.getMapHeight()); y++) {
FreerailsTile tt = (FreerailsTile) world.getTile(x, y);
if (!tt.getTrackPiece().equals(NullTrackPiece.getInstance())) {
double xDouble = x - visibleMapTiles.x;
xDouble = xDouble * scale;
double yDouble = y - visibleMapTiles.y;
yDouble = yDouble * scale;
g.drawRect((int) xDouble, (int) yDouble, 1, 1);
}
}
}
// Draw stations
while (it.next()) {
/*
* (1) The selected station is drawn green. (2) Non-selected
* stations which are on the schedule are drawn blue. (3) Other
* stations are drawn white. (4) If, for instance, station X is the
* first stop on the schedule, "1" is drawn above the station. (5)
* If, for instance, station X is the first and third stop on the
* schedule, "1, 3" is drawn above the station. (6) The stop numbers
* drawn above the stations are drawn using the same colour as used
* to draw the station.
*/
StationModel station = (StationModel) it.getElement();
double x = station.x - visibleMapTiles.x;
x = x * scale;
double y = station.y - visibleMapTiles.y;
y = y * scale;
int xInt = (int) x;
int yInt = (int) y;
String stopNumbersString = "";
boolean stationIsOnSchedule = false;
for (int orderNumber = 0; orderNumber < schedule.getNumOrders(); orderNumber++) {
int stationID = orderNumber == this.selectedOrderNumber ? this.selectedStationID
: schedule.getOrder(orderNumber).getStationID();
if (it.getIndex() == stationID) {
if (stationIsOnSchedule) {
stopNumbersString = stopNumbersString + ", "
+ String.valueOf(orderNumber + 1);
} else {
stopNumbersString = String.valueOf(orderNumber + 1);
}
stationIsOnSchedule = true;
}
}
if (stationIsOnSchedule) {
if (it.getIndex() == selectedStationID) {
g2.setColor(Color.GREEN);
} else {
g2.setColor(Color.BLUE);
}
g2.drawString(stopNumbersString, xInt, yInt - 4);
} else {
g2.setColor(Color.WHITE);
}
g2.fillRect(xInt, yInt, 10, 10);
}
}
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
cargoWaitingAndDemandedJPanel1.setup(mr, vl, null);
this.world = mr.getWorld();
this.submitButtonCallBack = closeAction;
principal = mr.getPrincipal();
}
public MutableSchedule generateNewSchedule() {
TrainOrdersModel oldOrders, newOrders;
oldOrders = schedule.getOrder(selectedOrderNumber);
newOrders = new TrainOrdersModel(selectedStationID, oldOrders
.getConsist(), oldOrders.getWaitUntilFull(), oldOrders
.isAutoConsist());
schedule.setOrder(selectedOrderNumber, newOrders);
return schedule;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private jfreerails.client.view.CargoWaitingAndDemandedJPanel cargoWaitingAndDemandedJPanel1;
private javax.swing.JLabel jLabel1;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
display
formComponentResized
formComponentShown
formKeyPressed
formMouseClicked
formMouseMoved
generateNewSchedule
initComponents/**
paintComponent
setZoom/**
setup
jfreerails.client.view.SelectWagonsJPanel
Javadoc:
/** * This JPanel lets the user add wagons to a train. * * @author lindsal8 * */
Source code:
/**
* This JPanel lets the user add wagons to a train.
*
* @author lindsal8
*
*/
public class SelectWagonsJPanel extends javax.swing.JPanel implements View {
private static final long serialVersionUID = 3905239009449095220L;
private final GraphicsConfiguration defaultConfiguration = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
private final Image stationView;
private final ArrayList<Integer> wagons = new ArrayList<Integer>();
private int engineType = 0;
private RenderersRoot rr;
public SelectWagonsJPanel() {
initComponents();
updateMaxWagonsText();
URL url = SelectWagonsJPanel.class
.getResource("/jfreerails/data/station.gif");
Image tempImage = (new javax.swing.ImageIcon(url)).getImage();
stationView = defaultConfiguration.createCompatibleImage(tempImage
.getWidth(null), tempImage.getHeight(null),
Transparency.BITMASK);
Graphics g = stationView.getGraphics();
g.drawImage(tempImage, 0, 0, null);
}
public void resetSelectedWagons() {
this.wagons.clear();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
wagonTypesJList = new javax.swing.JList();
okjButton = new javax.swing.JButton();
clearjButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
setBackground(new java.awt.Color(0, 255, 51));
setMinimumSize(new java.awt.Dimension(640, 400));
setPreferredSize(new java.awt.Dimension(620, 380));
jPanel1.setLayout(new java.awt.GridBagLayout());
jPanel1.setMinimumSize(new java.awt.Dimension(170, 300));
jPanel1.setPreferredSize(new java.awt.Dimension(170, 300));
wagonTypesJList.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyTyped(java.awt.event.KeyEvent evt) {
wagonTypesJListKeyTyped(evt);
}
});
wagonTypesJList.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
wagonTypesJListMouseClicked(evt);
}
});
jScrollPane1.setViewportView(wagonTypesJList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel1.add(jScrollPane1, gridBagConstraints);
okjButton.setText("OK");
okjButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonAction(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
jPanel1.add(okjButton, gridBagConstraints);
clearjButton.setText("Clear");
clearjButton.setActionCommand("clear");
clearjButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel1.add(clearjButton, gridBagConstraints);
jLabel1.setFont(new java.awt.Font("Dialog", 0, 10));
jLabel1.setText("The maximum train length is 6 wagons");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 8);
jPanel1.add(jLabel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(20, 400, 70, 10);
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
add(jPanel1, gridBagConstraints);
}// GEN-END:initComponents
private void okButtonAction(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_okButtonAction
// Add your handling code here:
} // GEN-LAST:event_okButtonAction
private void wagonTypesJListMouseClicked(java.awt.event.MouseEvent evt) { // GEN-FIRST:event_wagonTypesJListMouseClicked
// Add your handling code here:
addwagon();
} // GEN-LAST:event_wagonTypesJListMouseClicked
private void wagonTypesJListKeyTyped(java.awt.event.KeyEvent evt) { // GEN-FIRST:event_wagonTypesJListKeyTyped
// Add your handling code here:
if (KeyEvent.VK_ENTER == evt.getKeyCode()) {
addwagon();
} else {
}
} // GEN-LAST:event_wagonTypesJListKeyTyped
// Adds the wagon selected in the list to the train consist.
private void addwagon() {
if (wagons.size() < TrainModel.MAX_NUMBER_OF_WAGONS) {
int type = wagonTypesJList.getSelectedIndex();
wagons.add(new Integer(type));
updateMaxWagonsText();
this.repaint();
}
}
private void updateMaxWagonsText() {
if (wagons.size() >= TrainModel.MAX_NUMBER_OF_WAGONS) {
jLabel1.setText("Max train length is "
+ TrainModel.MAX_NUMBER_OF_WAGONS + " wagons");
} else {
jLabel1.setText("");
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton1ActionPerformed
// Add your handling code here:
wagons.clear();
jLabel1.setText("");
this.repaint();
} // GEN-LAST:event_jButton1ActionPerformed
@Override
public void paint(Graphics g) {
// paint the background
g.drawImage(this.stationView, 0, 0, null);
int x = this.getWidth();
int y = 330;
final int SCALED_IMAGE_HEIGHT = 50;
// paint the wagons
for (int i = this.wagons.size() - 1; i >= 0; i--) { // Count down so we
// paint the wagon
// at the end of the
// train first.
Integer type = wagons.get(i);
Image image = rr.getWagonImages(type.intValue()).getSideOnImage();
int scaledWidth = image.getWidth(null) * SCALED_IMAGE_HEIGHT
/ image.getHeight(null);
x -= scaledWidth;
g.drawImage(image, x, y, scaledWidth, SCALED_IMAGE_HEIGHT, null);
}
// paint the engine
if (-1 != this.engineType) { // If an engine is selected.
Image image = rr.getEngineImages(engineType).getSideOnImage();
int scaledWidth = (image.getWidth(null) * SCALED_IMAGE_HEIGHT)
/ image.getHeight(null);
x -= scaledWidth;
g.drawImage(image, x, y, scaledWidth, SCALED_IMAGE_HEIGHT, null);
}
this.paintChildren(g);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton clearjButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton okjButton;
private javax.swing.JList wagonTypesJList;
// End of variables declaration//GEN-END:variables
final private class WagonCellRenderer implements ListCellRenderer {
private final Component[] labels;
final RenderersRoot rr;
public WagonCellRenderer(World2ListModelAdapter w2lma, RenderersRoot s) {
rr = s;
labels = new Component[w2lma.getSize()];
for (int i = 0; i < w2lma.getSize(); i++) {
JLabel label = new JLabel();
label.setFont(new java.awt.Font("Dialog", 0, 12));
Image image = rr.getWagonImages(i).getSideOnImage();
int height = image.getHeight(null);
int width = image.getWidth(null);
int scale = height / 10;
ImageIcon icon = new ImageIcon(image.getScaledInstance(width
/ scale, height / scale, Image.SCALE_FAST));
label.setIcon(icon);
labels[i] = label;
}
}
public Component getListCellRendererComponent(JList list, Object value, /*
* value
* to
* display
*/
int index, /* cell index */
boolean isSelected, /* is the cell selected */
boolean cellHasFocus) /* the list and the cell have the focus */{
if (index >= 0 && index < labels.length) {
CargoType cargoType = (CargoType) value;
String text = "<html><body>"
+ (isSelected ? "<strong>" : "")
+ cargoType.getDisplayName()
+ (isSelected ? "</strong>"
: "&nbsp;&nbsp;&nbsp;&nbsp;"/*
* padding to stop
* word wrap due to
* greater width of
* strong font
*/) + "</body></html>";
((JLabel) labels[index]).setText(text);
return labels[index];
}
return null;
}
}
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
World2ListModelAdapter w2lma = new World2ListModelAdapter(
mr.getWorld(), SKEY.CARGO_TYPES);
this.wagonTypesJList.setModel(w2lma);
this.rr = vl;
WagonCellRenderer wagonCellRenderer = new WagonCellRenderer(w2lma,
rr);
this.wagonTypesJList.setCellRenderer(wagonCellRenderer);
this.okjButton.addActionListener(closeAction);
}
public int[] getWagons() {
int[] wagonsArray = new int[wagons.size()];
for (int i = 0; i < wagons.size(); i++) {
Integer type = wagons.get(i);
wagonsArray[i] = type.intValue();
}
return wagonsArray;
}
public void setEngineType(int engineType) {
this.engineType = engineType;
}
}
Methods:
MethodJavadoc
addwagon
getWagons
initComponents/**
jButton1ActionPerformed
okButtonAction
paint
resetSelectedWagons
setEngineType
setup/**
updateMaxWagonsText
wagonTypesJListKeyTyped
wagonTypesJListMouseClicked
jfreerails.client.view.ServerControlModel
Javadoc:
/** * Exposes the ServerControlInterface to client UI implementations. * * @author rob * @author Luke * @author MystiqueAgent */
Source code:
/**
* Exposes the ServerControlInterface to client UI implementations.
*
* @author rob
* @author Luke
* @author MystiqueAgent
*/
public class ServerControlModel implements ModelRootListener{
private class LoadGameAction extends AbstractAction {
private static final long serialVersionUID = 3616451215278682931L;
public LoadGameAction() {
putValue(NAME, "Load Game");
putValue(MNEMONIC_KEY, new Integer(76));
}
public void actionPerformed(ActionEvent e) {
dbc.showSelectSavedGame2Load();
/*
ImStringList files = (ImStringList)modelRoot.getProperty(Property.SAVED_GAMES_LIST);
Object[] saves = new Object[files.size()];
for (int i = 0; i < files.size(); i++) {
saves[i] = files.get(i);
}
// Display a JOptionPane that lists the existing saved games
try {
Object showInputDialog = JOptionPane.showInputDialog(null,
"Saved Games:", "Select game to load",
JOptionPane.INFORMATION_MESSAGE, null, saves, saves[0]);
String filename = showInputDialog.toString();
// Load the game chosen
Message2Server message2 = new LoadGameMessage2Server(1,
filename);
modelRoot.sendCommand(message2);
} catch (Exception exept) {
// <Hack>
// When no saved game is selected, or one that doesnt exist,
// nothing changes
// </.Hack>
}
*/
}
}
private class NewGameAction extends AbstractAction {
private static final long serialVersionUID = 3690758388631745337L;
public NewGameAction(String s) {
if (s == null) {
putValue(NAME, "New Game...");
} else {
putValue(NAME, s);
putValue(ACTION_COMMAND_KEY, s);
}
}
public void actionPerformed(ActionEvent e) {
String mapName = e.getActionCommand();
if (mapName != null) {
Message2Server message2 = new NewGameMessage2Server(1, mapName);
modelRoot.sendCommand(message2);
}
}
}
private class SaveGameAction extends AbstractAction {
private static final long serialVersionUID = 3905808578064562480L;
public SaveGameAction() {
putValue(NAME, "Save Game");
putValue(MNEMONIC_KEY, new Integer(83));
}
public void actionPerformed(ActionEvent e) {
dbc.showSaveGame();
/*
try {
// @SonnyZ
// Show a JOptionPane that takes in a string from a text box
String filename = JOptionPane.showInputDialog(null,
"Saved Game Name:", "Save Game",
JOptionPane.QUESTION_MESSAGE, null, null,
modelRoot.getPrincipal().getName()).toString();
// Save the current game using the string
modelRoot.setProperty(Property.QUICK_MESSAGE, "Saved game "
+ filename);
Message2Server message2 = new SaveGameMessage2Server(1,
filename + ".sav");
modelRoot.sendCommand(message2);
loadGameAction.setEnabled(true);
} catch (Exception except) {
}
*/
}
}
private class SetTargetTicksPerSecondAction extends AbstractAction {
private static final long serialVersionUID = 3256437014978048052L;
final int speed;
/**
* Same as the constructor above but it enables also to associate a
* <code>keyEvent</code> with the action.
*
* @param name
* action name
* @param speed
* speed
* @param keyEvent
* associated key event. Use values from
* <code>KeyEvent</class>.
*
* by MystiqueAgent
*/
public SetTargetTicksPerSecondAction(String name, int speed,
int keyEvent) {
putValue(NAME, name);
this.speed = speed;
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(keyEvent, 0));
}
public void actionPerformed(ActionEvent e) {
int speed2set = speed;
if (speed == 0) { // pausing/unpausing
speed2set = -1 * getTargetTicksPerSecond();
}
modelRoot.doMove(ChangeGameSpeedMove.getMove(modelRoot.getWorld(),
new GameSpeed(speed2set)));
}
}
private final Action loadGameAction = new LoadGameAction();
private ModelRootImpl modelRoot;
private final Action newGameAction = new NewGameAction(null);
private final Action saveGameAction = new SaveGameAction();
private ActionAdapter selectMapActions;
private final SetTargetTicksPerSecondAction[] speedActions = new SetTargetTicksPerSecondAction[] {
new SetTargetTicksPerSecondAction("Pause", 0, KeyEvent.VK_P),
new SetTargetTicksPerSecondAction("Slow", 10, KeyEvent.VK_1),
new SetTargetTicksPerSecondAction("Moderate", 30, KeyEvent.VK_2),
new SetTargetTicksPerSecondAction("Fast", 70, KeyEvent.VK_3),
};
private final ActionAdapter targetTicksPerSecondActions = new ActionAdapter(
speedActions, 0);
private DialogueBoxController dbc;
public ServerControlModel(ModelRootImpl mr) {
this.modelRoot = mr;
mr.addPropertyChangeListener(this);
setServerControlInterface();
}
/**
* Returns human readable string description of <code>tickPerSecond</code>
* number. Looks for <code>tickPerSecond</code> in
* <code>targetTicksPerSecondActions</code>. If appropriate action is not
* found returns first greater value or the greatest value.
*
* @param tickPerSecond
* int
* @return String human readable description
*/
public String getGameSpeedDesc(int tickPerSecond) {
SetTargetTicksPerSecondAction action = null;
for (int i = 0; i < speedActions.length; i++) {
action = speedActions[i];
if (action.speed >= tickPerSecond)
break;
}
return (String) action.getValue(Action.NAME);
}
/**
* @return an action to load a game.
*/
public Action getLoadGameAction() {
return loadGameAction;
}
/**
* @return an ActionAdapter representing a list of actions representing
* valid map names.
*/
public ActionAdapter getMapNames() {
return selectMapActions;
}
/**
* When calling this action, set the action command string to the desired
* map name, or call the appropriate selectMapAction.
*
* @return an action to start a new game
*/
public Action getNewGameAction() {
return newGameAction;
}
/**
* @return an action to save a game TODO The action produces a file selector
* dialog to save the game
*/
public Action getSaveGameAction() {
return saveGameAction;
}
/**
* @return an action adapter to set the target ticks per second
*/
public ActionAdapter getSetTargetTickPerSecondActions() {
return targetTicksPerSecondActions;
}
public int getTargetTicksPerSecond() {
ReadOnlyWorld world = modelRoot.getWorld();
return ((GameSpeed) world.get(ITEM.GAME_SPEED)).getSpeed();
}
public void propertyChange(Property p, Object oldValue, Object newValue) {
// switch (p) {
// case SAVED_GAMES_LIST:
// updateLoadGameAction();
// break;
//
// default:
// break;
// }
}
public void setup(ModelRootImpl modelRoot, DialogueBoxController dbc) {
this.modelRoot = modelRoot;
this.dbc = dbc;
modelRoot.addPropertyChangeListener(this);
}
public void setServerControlInterface() {
// Check that there is a file to load..
saveGameAction.setEnabled(true);
Enumeration<Action> e = targetTicksPerSecondActions.getActions();
targetTicksPerSecondActions.setPerformActionOnSetSelectedItem(false);
while (e.hasMoreElements()) {
e.nextElement().setEnabled(true);
}
String[] mapNames = NewGameMessage2Server.getMapNames();
Action[] actions = new Action[mapNames.length];
for (int j = 0; j < actions.length; j++) {
actions[j] = new NewGameAction(mapNames[j]);
actions[j].setEnabled(true);
}
selectMapActions = new ActionAdapter(actions);
newGameAction.setEnabled(true);
}
}
Methods:
MethodJavadoc
getGameSpeedDesc/**
getLoadGameAction/**
getMapNames/**
getNewGameAction/**
getSaveGameAction/**
getSetTargetTickPerSecondActions/**
getTargetTicksPerSecond
propertyChange
setServerControlInterface
setup/**
jfreerails.client.view.ShowJavaProperties
Javadoc:
/** * This class returns the Java System Properties as an HTML table. * * @author Luke * */
Source code:
/**
* This class returns the Java System Properties as an HTML table.
*
* @author Luke
*
*/
public class ShowJavaProperties {
public static final int TABLE_WIDTH = 500;
private static final Logger logger = Logger
.getLogger(ShowJavaProperties.class.getName());
public static void main(String[] args) {
logger.info(getPropertiesHtmlString());
}
public static String getPropertiesHtmlString() {
Properties p = System.getProperties();
StringBuffer sb = new StringBuffer();
/* We set the width of the table so that its text word-wraps. */
sb.append("<html><h3>Java System Properties</h3><table width =\""
+ TABLE_WIDTH + "\" align = \"left\" valign = \"top\">\n");
Enumeration keys = p.keys();
//We use an ArrayList so that the keys can be sorted into alphabetical order
ArrayList<String> list = new ArrayList<String>();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
list.add(key);
}
Collections.sort(list);
for(String key : list){
String value = p.getProperty(key);
/*
* Insert a line break after each ";". This makes reading classpath
* elements easier.
*/
value = value.replaceAll(";", ";<br>");
sb
.append("<tr><td>" + key + " </td><td> " + value
+ "</td></tr>\n");
}
sb.append("</table></html>\n");
return sb.toString();
}
}
Methods:
MethodJavadoc
getPropertiesHtmlString
main
jfreerails.client.view.StationBuildModel
Javadoc:
/** * This class provides the UI model for building a station. The mode of * operation is as follows: * <ol> * <li>Select a station to build by calling ActionPerformed() on the choose * Action. * <li>Set the position to build. * <li>call actionPerformed on the build Action * <li> alternatively, call actionPerformed on the cancel Action * </ol> * * @author rob */
Source code:
/**
* This class provides the UI model for building a station. The mode of
* operation is as follows:
* <ol>
* <li>Select a station to build by calling ActionPerformed() on the choose
* Action.
* <li>Set the position to build.
* <li>call actionPerformed on the build Action
* <li> alternatively, call actionPerformed on the cancel Action
* </ol>
*
* @author rob
*/
public class StationBuildModel {
/*
* 100 010 001 = 0x111
*/
private static final int trackTemplate = TrackConfiguration
.from9bitTemplate(0x111).get9bitTemplate();
/**
* Vector of StationBuildAction. Actions which represent stations which can
* be built
*/
private final Vector<Action> stationChooseActions = new Vector<Action>();
/**
* Whether the station's position can should change when the mouse moves.
*/
private boolean positionFollowsMouse = true;
private final StationBuildAction stationBuildAction = new StationBuildAction();
private final StationCancelAction stationCancelAction = new StationCancelAction();
private final StationBuilder stationBuilder;
private final ModelRoot modelRoot;
private final HashMap<Integer, Action> id2Action = new HashMap<Integer, Action>();
public StationBuildModel(StationBuilder sb, RenderersRoot rr, ModelRoot mr) {
stationBuilder = sb;
modelRoot = mr;
ReadOnlyWorld world = modelRoot.getWorld();
for (int i = 0; i < world.size(SKEY.TRACK_RULES); i++) {
final TrackRule trackRule = (TrackRule) world.get(
SKEY.TRACK_RULES, i);
if (trackRule.isStation()) {
TrackPieceRenderer renderer = rr.getTrackPieceView(i);
StationChooseAction action = new StationChooseAction(i);
String trackType = trackRule.getTypeName();
Money price = trackRule.getFixedCost();
String shortDescrpt = Utils.capitalizeEveryWord(trackType)
+ " $" + price.toString();
action.putValue(Action.SHORT_DESCRIPTION, shortDescrpt);
action.putValue(Action.NAME, "Build " + trackType);
action.putValue(Action.SMALL_ICON, new ImageIcon(renderer
.getTrackPieceIcon(trackTemplate)));
stationChooseActions.add(action);
id2Action.put(new Integer(i), action);
}
}
}
public Action getStationChooseAction(Integer ruleID) {
return id2Action.get(ruleID);
}
public Action[] getStationChooseActions() {
return stationChooseActions.toArray(new Action[stationChooseActions.size()]);
}
private class StationChooseAction extends AbstractAction {
private static final long serialVersionUID = 3257290240279458098L;
private final int actionId;
public StationChooseAction(int actionId) {
this.actionId = actionId;
}
public void actionPerformed(ActionEvent e) {
stationBuilder.setStationType(actionId);
TrackRule trackRule = (TrackRule) modelRoot.getWorld().get(
SKEY.TRACK_RULES, actionId);
// Show the relevant station radius when the station type's menu
// item
// gets focus.
stationBuildAction.putValue(StationBuildAction.STATION_RADIUS_KEY,
new Integer(trackRule.getStationRadius()));
stationBuildAction.setEnabled(true);
}
}
private class StationCancelAction extends AbstractAction {
private static final long serialVersionUID = 3256441421581203252L;
public void actionPerformed(ActionEvent e) {
stationBuildAction.setEnabled(false);
}
}
/**
* This action builds the station.
*/
public class StationBuildAction extends AbstractAction {
private static final long serialVersionUID = 3905236827739926833L;
/**
* This key can be used to set the position where the station is to be
* built as a Point object.
*/
public final static String STATION_POSITION_KEY = "STATION_POSITION_KEY";
/**
* This key can be used to retrieve the radius of the currently selected
* station as an Integer value. Don't bother writing to it!
*/
public final static String STATION_RADIUS_KEY = "STATION_RADIUS_KEY";
StationBuildAction() {
setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
Point value = (Point) stationBuildAction
.getValue(StationBuildAction.STATION_POSITION_KEY);
MoveStatus ms = stationBuilder.buildStation(new ImPoint(value.x,
value.y));
String message = null;
if (ms.isOk()) {
stationBuildAction.setEnabled(false);
} else {
message = ms.message;
}
modelRoot.setProperty(ModelRoot.Property.CURSOR_MESSAGE, message);
}
}
public boolean canBuildStationHere() {
Point p = (Point) stationBuildAction
.getValue(StationBuildAction.STATION_POSITION_KEY);
return stationBuilder.tryBuildingStation(new ImPoint(p.x, p.y)).ok;
}
public Action getStationCancelAction() {
return stationCancelAction;
}
public StationBuildAction getStationBuildAction() {
return stationBuildAction;
}
public boolean isPositionFollowsMouse() {
return positionFollowsMouse;
}
public void setPositionFollowsMouse(boolean positionFollowsMouse) {
this.positionFollowsMouse = positionFollowsMouse;
}
}
Methods:
MethodJavadoc
canBuildStationHere
getStationBuildAction
getStationCancelAction
getStationChooseAction
getStationChooseActions
isPositionFollowsMouse
setPositionFollowsMouse
jfreerails.client.view.StationInfoJPanel
Javadoc:
/** * This JPanel displays the supply and demand at a station. * * @author Luke */
Source code:
/**
* This JPanel displays the supply and demand at a station.
*
* @author Luke
*/
public class StationInfoJPanel extends JPanel implements View,
WorldListListener {
private static final long serialVersionUID = 4050759377680150585L;
private ReadOnlyWorld w;
private ModelRoot modelRoot;
private WorldIterator wi;
/**
* The index of the cargoBundle associated with this station.
*/
private int cargoBundleIndex;
public StationInfoJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jLabel1 = new javax.swing.JLabel();
nextStation = new javax.swing.JButton();
previousStation = new javax.swing.JButton();
close = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
setMinimumSize(new java.awt.Dimension(250, 177));
jLabel1.setFont(new java.awt.Font("Dialog", 0, 10));
jLabel1
.setText("<html>\n<h4 align=\"center\">Supply and Demand at stationName</h4>\n<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"2\">\n <tr>\n <td>&nbsp;</td>\n <td>Will pay<br>for</td>\n <td>Supplies<br>(cars per year)</td>\n <td>Waiting for pickup<br>(car loads)</td>\n </tr>\n <tr>\n <td>Mail</td>\n <td>Yes</td>\n <td>&nbsp;</td>\n <td>&nbsp;</td>\n </tr>\n <tr>\n <td>Passengers</td>\n <td>No</td>\n <td>3</td>\n <td>2.5</td>\n </tr>\n \n</table>\n\n</html>");
jLabel1.setVerticalAlignment(javax.swing.SwingConstants.TOP);
jLabel1.setAlignmentY(0.0F);
jLabel1.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 4, 8);
add(jLabel1, gridBagConstraints);
nextStation.setText("next ->");
nextStation.setMargin(new java.awt.Insets(0, 0, 0, 0));
nextStation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextStationActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(nextStation, gridBagConstraints);
previousStation.setText("<- previous");
previousStation.setMargin(new java.awt.Insets(0, 0, 0, 0));
previousStation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
previousStationActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(previousStation, gridBagConstraints);
close.setText("close");
close.setMargin(new java.awt.Insets(0, 0, 0, 0));
close.setMaximumSize(new java.awt.Dimension(65, 22));
close.setMinimumSize(new java.awt.Dimension(65, 22));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(close, gridBagConstraints);
}// GEN-END:initComponents
private void previousStationActionPerformed(java.awt.event.ActionEvent evt) {
// GEN-FIRST:event_previousStationActionPerformed
// Add your handling code here:
if (wi.previous()) {
ImPoint p = new ImPoint(((StationModel) wi.getElement())
.getStationX(), ((StationModel) wi.getElement())
.getStationY());
this.modelRoot.setProperty(ModelRoot.Property.CURSOR_POSITION, p);
display();
} else {
throw new IllegalStateException();
}
} // GEN-LAST:event_previousStationActionPerformed
private void nextStationActionPerformed(java.awt.event.ActionEvent evt) {
// GEN-FIRST:event_nextStationActionPerformed
// Add your handling code here:
if (wi.next()) {
ImPoint p = new ImPoint(((StationModel) wi.getElement())
.getStationX(), ((StationModel) wi.getElement())
.getStationY());
this.modelRoot.setProperty(ModelRoot.Property.CURSOR_POSITION, p);
display();
} else {
throw new IllegalStateException();
}
} // GEN-LAST:event_nextStationActionPerformed
public void setup(ModelRoot mr, RenderersRoot vl, Action al) {
this.wi = new NonNullElements(KEY.STATIONS, mr.getWorld(), mr
.getPrincipal());
addComponentListener(componentListener);
this.w = mr.getWorld();
this.modelRoot = mr;
this.close.addActionListener(al);
}
public void setStation(int stationNumber) {
this.wi.gotoIndex(stationNumber);
display();
}
private void display() {
if (wi.getRowID() > 0) {
this.previousStation.setEnabled(true);
} else {
this.previousStation.setEnabled(false);
}
if (wi.getRowID() < (wi.size() - 1)) {
this.nextStation.setEnabled(true);
} else {
this.nextStation.setEnabled(false);
}
int stationNumber = wi.getIndex();
String label;
if (stationNumber != WorldIterator.BEFORE_FIRST) {
StationModel station = (StationModel) w.get(modelRoot.getPrincipal(),
KEY.STATIONS, stationNumber);
FreerailsTile tile = (FreerailsTile) w
.getTile(station.x, station.y);
String stationTypeName = tile.getTrackPiece().getTrackRule().getTypeName();
cargoBundleIndex = station.getCargoBundleID();
ImmutableCargoBundle cargoWaiting = (ImmutableCargoBundle) w.get(
modelRoot
.getPrincipal(), KEY.CARGO_BUNDLES, station.getCargoBundleID());
String title = "<h2 align=\"center\">" + station.getStationName()
+ " (" + stationTypeName + ")</h2>";
String table = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"3\"><tr><td>&nbsp;</td>\n <td>Will pay for</td>\n <td>Supplies / cars per year</td><td>Waiting for pickup / car loads</td> </tr>";
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
// get the values
CargoType cargoType = (CargoType) w.get(SKEY.CARGO_TYPES, i);
String demanded = (station.getDemand().isCargoDemanded(i) ? "Yes"
: "No");
int amountSupplied = station.getSupply().getSupply(i);
String supply = (amountSupplied > 0) ? String
.valueOf(amountSupplied
/ WagonType.UNITS_OF_CARGO_PER_WAGON)
: "&nbsp;";
int amountWaiting = cargoWaiting.getAmount(i);
String waiting = (amountWaiting > 0) ? String
.valueOf(amountWaiting
/ WagonType.UNITS_OF_CARGO_PER_WAGON)
: "&nbsp;";
// build the html
table += "<tr>";
table += "<td>" + cargoType.getDisplayName() + "</td>";
table += "<td>" + demanded + "</td>";
table += "<td>" + supply + "</td>";
table += "<td>" + waiting + "</td>";
table += "</tr>";
}
table += "</table>";
label = "<html>" + title + table + "</html>";
} else {
cargoBundleIndex = WorldIterator.BEFORE_FIRST;
label = "<html><h2 align=\"center\">No Station "
+ "Selected</h2></html>";
}
jLabel1.setText(label);
this.repaint();
}
private final ComponentAdapter componentListener = new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) {
int i = wi.getIndex();
wi.reset();
if (i != WorldIterator.BEFORE_FIRST) {
wi.gotoIndex(i);
}
display();
}
};
private FreerailsSerializable lastCargoBundle = null;
@Override
protected void paintComponent(Graphics g) {
/* We need to update if the cargo bundle has changed. */
FreerailsPrincipal playerPrincipal = this.modelRoot.getPrincipal();
/*
* Avoid a array out of bounds exception when there are no stations and
* the stations tab is visible.
*/
if (w.boundsContain(playerPrincipal, KEY.CARGO_BUNDLES,
cargoBundleIndex)) {
FreerailsSerializable currentCargoBundle = w.get(playerPrincipal,
KEY.CARGO_BUNDLES, this.cargoBundleIndex);
if (lastCargoBundle != currentCargoBundle) {
this.display();
lastCargoBundle = currentCargoBundle;
}
}
super.paintComponent(g);
}
private void reactToUpdate(KEY key, int changedIndex, boolean isAddition) {
if (!isVisible()) {
return;
}
int currentIndex = wi.getIndex();
if (key == KEY.CARGO_BUNDLES) {
if (changedIndex == cargoBundleIndex) {
/* update our cargo bundle */
display();
return;
}
} else if (key == KEY.STATIONS) {
wi.reset();
if (currentIndex != WorldIterator.BEFORE_FIRST) {
if (currentIndex < wi.size()) {
wi.gotoIndex(currentIndex);
} else {
currentIndex = WorldIterator.BEFORE_FIRST;
}
}
if (isAddition && wi.getIndex() == WorldIterator.BEFORE_FIRST) {
if (wi.next()) {
display();
}
}
if (currentIndex == changedIndex
|| currentIndex == WorldIterator.BEFORE_FIRST) {
display();
}
}
return;
}
public void listUpdated(KEY key, int index, FreerailsPrincipal principal) {
if (modelRoot.getPrincipal().equals(principal))
reactToUpdate(key, index, false);
}
public void itemAdded(KEY key, int index, FreerailsPrincipal principal) {
if (modelRoot.getPrincipal().equals(principal))
reactToUpdate(key, index, true);
}
public void itemRemoved(KEY key, int index, FreerailsPrincipal principal) {
if (modelRoot.getPrincipal().equals(principal))
reactToUpdate(key, index, false);
}
void removeCloseButton() {
this.remove(close);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton close;
private javax.swing.JLabel jLabel1;
private javax.swing.JButton nextStation;
private javax.swing.JButton previousStation;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
display
initComponents/**
itemAdded
itemRemoved
listUpdated
nextStationActionPerformed
paintComponent
previousStationActionPerformed
reactToUpdate
removeCloseButton
setStation
setup
jfreerails.client.view.StationPlacementCursor
Javadoc:
/** * This class implements a cursor which can be used to place a station on the * map. Mode of operation: * <ol> * <li>User selects a station to place, which sets the current cursor to the * station placement cursor. * <li>User highlights desired build location with the mouse, boundary of the * station radius is highlighted. If the station cannot be built, the boundary * highlights in red. * <li>User places station with the left mouse button. * <li>User may cancel placement by using the right mouse button * <li>Cursor fires the actionPerformed causing the station to be built. * </ol> * When the StationBuildAction is no longer enabled, the owner reverts to the * regular cursor type. TODO scroll the area when the mouse hovers at the edge * of the map. * * @author rob */
Source code:
/**
* This class implements a cursor which can be used to place a station on the
* map. Mode of operation:
* <ol>
* <li>User selects a station to place, which sets the current cursor to the
* station placement cursor.
* <li>User highlights desired build location with the mouse, boundary of the
* station radius is highlighted. If the station cannot be built, the boundary
* highlights in red.
* <li>User places station with the left mouse button.
* <li>User may cancel placement by using the right mouse button
* <li>Cursor fires the actionPerformed causing the station to be built.
* </ol>
* When the StationBuildAction is no longer enabled, the owner reverts to the
* regular cursor type. TODO scroll the area when the mouse hovers at the edge
* of the map.
*
* @author rob
*/
public class StationPlacementCursor extends MouseInputAdapter {
public static void wireUp(ActionRoot actionRoot, StationRadiusRenderer srr,
MapViewJComponent mapView) {
StationPlacementCursor spc = new StationPlacementCursor(actionRoot,
srr, mapView);
spc.init();
}
private final PropertyChangeListener buildActionListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName().equals(
StationBuildModel.StationBuildAction.STATION_POSITION_KEY)) {
/* update the renderer pos */
Point p = (Point) e.getNewValue();
stationRadiusRenderer.setPosition(p.x, p.y);
if (stationBuildModel.canBuildStationHere()) {
stationRadiusRenderer
.setBorderColor(StationRadiusRenderer.COLOR_OK);
} else {
stationRadiusRenderer
.setBorderColor(StationRadiusRenderer.COLOR_CANNOT_BUILD);
}
} else if (e.getPropertyName().equals(
StationBuildModel.StationBuildAction.STATION_RADIUS_KEY)) {
Integer radius = (Integer) e.getNewValue();
stationRadiusRenderer.setRadius(radius.intValue());
}
boolean enabled = stationBuildModel.getStationBuildAction()
.isEnabled();
if (buildEnabled != enabled) {
if (enabled) {
mapView.addMouseListener(StationPlacementCursor.this);
mapView.addMouseMotionListener(StationPlacementCursor.this);
stationRadiusRenderer.show();
} else {
stationRadiusRenderer.hide();
mapView.removeMouseListener(StationPlacementCursor.this);
mapView
.removeMouseMotionListener(StationPlacementCursor.this);
}
buildEnabled = enabled;
}
}
};
private boolean buildEnabled;
private final MapViewJComponent mapView;
private final float scale;
private final StationBuildModel stationBuildModel;
private final StationRadiusRenderer stationRadiusRenderer;
private StationPlacementCursor(ActionRoot actionRoot,
StationRadiusRenderer srr, MapViewJComponent mapView) {
scale = mapView.getScale();
this.mapView = mapView;
stationBuildModel = actionRoot.getStationBuildModel();
stationRadiusRenderer = srr;
buildEnabled = stationBuildModel.getStationBuildAction().isEnabled();
}
private void init() {
if (buildEnabled) {
mapView.addMouseListener(this);
mapView.addMouseMotionListener(this);
stationRadiusRenderer.show();
} else {
stationRadiusRenderer.hide();
mapView.removeMouseListener(this);
mapView.removeMouseMotionListener(this);
}
stationBuildModel.getStationBuildAction().addPropertyChangeListener(
buildActionListener);
}
@Override
public void mouseClicked(MouseEvent e) {
int button = e.getButton();
if (button == MouseEvent.BUTTON1) {
/* attempt to build */
stationBuildModel.getStationBuildAction().actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
} else if (button == MouseEvent.BUTTON3) {
/* cancel the build */
stationBuildModel.getStationCancelAction().actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
}
}
@Override
public void mouseEntered(MouseEvent e) {
stationRadiusRenderer.show();
}
@Override
public void mouseExited(MouseEvent e) {
stationRadiusRenderer.hide();
}
@Override
public void mouseMoved(MouseEvent e) {
if (stationBuildModel.isPositionFollowsMouse()) {
Point p = e.getPoint();
Point mapCoord = new Point((int) (p.x / scale), (int) (p.y / scale));
stationBuildModel.getStationBuildAction().putValue(
StationBuildModel.StationBuildAction.STATION_POSITION_KEY,
mapCoord);
}
}
}
Methods:
MethodJavadoc
init
mouseClicked
mouseEntered
mouseExited
mouseMoved
wireUp
jfreerails.client.view.TerrainInfoJPanel
Javadoc:
/** * This JPanel shows information on a terrain type. * * @author Luke */
Source code:
/**
* This JPanel shows information on a terrain type.
*
* @author Luke
*/
public class TerrainInfoJPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 3258131375164045363L;
private RenderersRoot rr;
private ReadOnlyWorld w;
public TerrainInfoJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
terrainImage = new javax.swing.JLabel();
terrainName = new javax.swing.JLabel();
terrainDescription = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
terrainImage.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/jfreerails/client/graphics/terrain/City_0.png")));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(8, 8, 4, 4);
add(terrainImage, gridBagConstraints);
terrainName.setFont(new java.awt.Font("Dialog", 1, 14));
terrainName.setText("City");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 8);
add(terrainName, gridBagConstraints);
terrainDescription.setFont(new java.awt.Font("Dialog", 0, 12));
terrainDescription
.setText("<html>\n<p>Right-of-Way costs X per mile. </p>\n<table width=\"75%\" >\n <tr> \n <td><strong>Supplies:</strong></td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td>Mail </td>\n <td>2</td>\n </tr>\n <tr> \n <td>Passengers</td>\n <td>2</td>\n </tr>\n <tr> \n <td> <strong>Demands</strong></td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td>Mail</td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td>Passengers</td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td><strong>Converts</strong></td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td>Livestock to Food</td>\n <td>&nbsp;</td>\n </tr>\n <tr>\n <td>Steel to Goods</td>\n <td>&nbsp;</td>\n </tr>\n</table>\n</html>");
terrainDescription.setVerticalAlignment(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 8, 4, 8);
add(terrainDescription, gridBagConstraints);
}// GEN-END:initComponents
public void setup(ReadOnlyWorld w, RenderersRoot vl) {
this.w = w;
this.rr = vl;
}
public void setTerrainType(int typeNumber) {
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES, typeNumber);
String row = "<p>Right-of-Way costs $" + type.getRightOfWay()
+ " per mile. </p>";
String tableString = "";
int cargosProduced = type.getProduction().size();
int cargosConsumed = type.getConsumption().size();
int cargosConverted = type.getConversion().size();
if ((cargosProduced + cargosConsumed + cargosConverted) > 0) {
// if the terrain type produces, consumes, or converts anything.
tableString = "<table width=\"75%\" >";
if (cargosProduced != 0) {
tableString += "<tr> <td><strong>Supplies</strong></td> <td>&nbsp;</td> </tr>";
for (int i = 0; i < cargosProduced; i++) {
Production p = type.getProduction().get(i);
CargoType c = (CargoType) w.get(SKEY.CARGO_TYPES, p
.getCargoType());
String supply = String.valueOf(p.getRate()
/ WagonType.UNITS_OF_CARGO_PER_WAGON);
tableString += "<tr> <td>" + c.getDisplayName()
+ " </td><td>" + supply + "</td></tr>";
}
}
if (cargosConsumed != 0) {
tableString += "<tr> <td><strong>Demands</strong></td> <td>&nbsp;</td> </tr>";
for (int i = 0; i < cargosConsumed; i++) {
Consumption p = type.getConsumption().get(i);
CargoType c = (CargoType) w.get(SKEY.CARGO_TYPES, p
.getCargoType());
tableString += "<tr> <td>" + c.getDisplayName()
+ " </td><td>&nbsp;</td></tr>";
}
}
if (cargosConverted != 0) {
tableString += "<tr> <td><strong>Converts</strong></td> <td>&nbsp;</td> </tr>";
for (int i = 0; i < cargosConverted; i++) {
Conversion p = type.getConversion().get(i);
CargoType input = (CargoType) w.get(SKEY.CARGO_TYPES, p
.getInput());
CargoType output = (CargoType) w.get(SKEY.CARGO_TYPES, p
.getOutput());
tableString += "<tr> <td colspan=\"2\">"
+ input.getDisplayName() + " to "
+ output.getDisplayName() + "</td></tr>";
}
}
tableString += "</table> ";
}
String labelString = "<html>" + row + tableString + "</html>";
terrainDescription.setText(labelString);
terrainName.setText(type.getDisplayName());
Image tileIcon = rr.getTileViewWithNumber(typeNumber)
.getDefaultIcon();
terrainImage.setIcon(new ImageIcon(tileIcon));
repaint();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel terrainDescription;
private javax.swing.JLabel terrainImage;
private javax.swing.JLabel terrainName;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
initComponents/**
setTerrainType
setup
jfreerails.client.view.TrainDescriptionJPanel
Javadoc:
/** * This JPanel displays a side-on view of a train and a summary of the cargo * that it is carrying. * * @author Luke Lindsay */
Source code:
/**
* This JPanel displays a side-on view of a train and a summary of the cargo
* that it is carrying.
*
* @author Luke Lindsay
*/
public class TrainDescriptionJPanel extends javax.swing.JPanel implements View{
private static final long serialVersionUID = 3977018444325664049L;
private ReadOnlyWorld w;
private FreerailsPrincipal principal;
private int trainNumber = -1;
private FreerailsSerializable lastTrain, lastCargoBundle;
public TrainDescriptionJPanel() {
initComponents();
}
@Override
protected void paintComponent(Graphics arg0) {
//Check whether the train or its cargo have changed since the last call to this method.
updateIfNecessary();
super.paintComponent(arg0);
}
private void updateIfNecessary() {
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
trainNumber);
for (int i = 0; i < train.getNumberOfWagons(); i++) {
// this.sideOnTrainViewJPanel1.addWagon(train.getWagon(i));
}
int cargoBundleID = train.getCargoBundleID();
FreerailsSerializable cb = w.get(
principal, KEY.CARGO_BUNDLES, cargoBundleID);
if(train != lastTrain || cb != lastCargoBundle)
displayTrain(trainNumber);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jLabel1 = new javax.swing.JLabel();
trainViewJPanel1 = new jfreerails.client.view.TrainListCellRenderer();
setLayout(new java.awt.GridBagLayout());
setBorder(new javax.swing.border.TitledBorder("Current Details"));
setPreferredSize(new java.awt.Dimension(250, 97));
jLabel1.setFont(new java.awt.Font("Dialog", 0, 12));
jLabel1
.setText("<html><head></head><body>Trains X: 20 passengers, 15 tons of mfg goods, 12 sacks of mail, and 7 tons of livestock.</body></html>");
jLabel1.setMinimumSize(new java.awt.Dimension(250, 17));
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
jLabel1.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jLabel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
add(trainViewJPanel1, gridBagConstraints);
}// GEN-END:initComponents
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
this.trainViewJPanel1.setup(mr, vl, closeAction);
trainViewJPanel1.setHeight(30);
trainViewJPanel1.setCenterTrain(true);
this.w = mr.getWorld();
principal = mr.getPrincipal();
}
public void displayTrain(int newTrainNumber) {
NonNullElements it = new NonNullElements(KEY.TRAINS, w, principal);
it.gotoIndex(newTrainNumber);
this.trainNumber = newTrainNumber;
trainViewJPanel1.display(newTrainNumber);
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
newTrainNumber);
for (int i = 0; i < train.getNumberOfWagons(); i++) {
// this.sideOnTrainViewJPanel1.addWagon(train.getWagon(i));
}
int cargoBundleID = train.getCargoBundleID();
ImmutableCargoBundle cb = (ImmutableCargoBundle) w.get(
principal, KEY.CARGO_BUNDLES, cargoBundleID);
String s = "Train #" + it.getNaturalNumber() + ": ";
int numberOfTypesInBundle = 0;
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
int amount = cb.getAmount(i);
if (0 != amount) {
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, i);
String cargoTypeName = ct.getDisplayName();
if (0 != numberOfTypesInBundle) {
s += "; ";
}
numberOfTypesInBundle++;
s += cargoTypeName + " (" + amount + ")";
}
}
if (0 == numberOfTypesInBundle) {
s += "no cargo";
}
s += ".";
this.jLabel1.setText(s);
this.lastCargoBundle = cb;
this.lastTrain = train;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private jfreerails.client.view.TrainListCellRenderer trainViewJPanel1;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
displayTrain
initComponents/**
paintComponent
setup
updateIfNecessary
jfreerails.client.view.TrainDialogueJPanel
Javadoc:
/** * JPanel that displays info on a train; it is composed of a * {@link TrainScheduleJPanel} and {@link TrainDescriptionJPanel}. * * @author Luke Lindsay */
Source code:
/**
* JPanel that displays info on a train; it is composed of a
* {@link TrainScheduleJPanel} and {@link TrainDescriptionJPanel}.
*
* @author Luke Lindsay
*/
public class TrainDialogueJPanel extends javax.swing.JPanel implements View,
WorldListListener {
private static final long serialVersionUID = 3257005466801157938L;
private static final Logger logger = Logger
.getLogger(TrainDialogueJPanel.class.getName());
private WorldIterator wi;
private ReadOnlyWorld w;
private FreerailsPrincipal principal;
public TrainDialogueJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
newTrainScheduleJPanel1 = new jfreerails.client.view.TrainScheduleJPanel();
trainDetailsJPanel1 = new TrainDescriptionJPanel();
previousJButton = new javax.swing.JButton();
nextJButton = new javax.swing.JButton();
trainListJButton = new javax.swing.JButton();
closeJButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(510, 400));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(newTrainScheduleJPanel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
add(trainDetailsJPanel1, gridBagConstraints);
previousJButton.setText("last");
previousJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
previousJButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(previousJButton, gridBagConstraints);
nextJButton.setText("next");
nextJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextJButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(nextJButton, gridBagConstraints);
trainListJButton.setText("Train list");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(trainListJButton, gridBagConstraints);
closeJButton.setText("Close");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(closeJButton, gridBagConstraints);
}// GEN-END:initComponents
private void previousJButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_previousJButtonActionPerformed
// Add your handling code here:
if (wi.previous()) {
display(wi.getIndex());
} else {
logger.warning("Couldn't get previous");
}
}// GEN-LAST:event_previousJButtonActionPerformed
private void nextJButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_nextJButtonActionPerformed
// Add your handling code here:
if (wi.next()) {
display(wi.getIndex());
} else {
logger.warning("Couldn't get next");
}
}// GEN-LAST:event_nextJButtonActionPerformed
public void setup(ModelRoot mr, RenderersRoot vl, Action al) {
newTrainScheduleJPanel1.setup(mr, vl, al);
trainDetailsJPanel1.setup(mr, vl, al);
this.setCancelButtonActionListener(al);
this.principal = mr.getPrincipal();
this.w = mr.getWorld();
}
public void display(int trainNumber) {
wi = new NonNullElements(KEY.TRAINS, w, principal);
wi.gotoIndex(trainNumber);
if (wi.getRowID() > 0) {
this.previousJButton.setEnabled(true);
} else {
this.previousJButton.setEnabled(false);
}
if (wi.getRowID() < (wi.size() - 1)) {
this.nextJButton.setEnabled(true);
} else {
this.nextJButton.setEnabled(false);
}
newTrainScheduleJPanel1.display(trainNumber);
trainDetailsJPanel1.displayTrain(trainNumber);
}
public void listUpdated(KEY key, int index, FreerailsPrincipal p) {
newTrainScheduleJPanel1.listUpdated(key, index, p);
}
public void itemAdded(KEY key, int index, FreerailsPrincipal p) {
}
public void itemRemoved(KEY key, int index, FreerailsPrincipal p) {
}
void setTrainDetailsButtonActionListener(ActionListener l) {
ActionListener[] oldListeners = trainListJButton.getActionListeners();
for (int i = 0; i < oldListeners.length; i++) {
trainListJButton.removeActionListener(oldListeners[i]);
}
this.trainListJButton.addActionListener(l);
}
/**
* Removes any existing ActionListener listeners from the cancel button,
* then adds the specified one.
*/
void setCancelButtonActionListener(ActionListener l) {
ActionListener[] oldListeners = closeJButton.getActionListeners();
for (int i = 0; i < oldListeners.length; i++) {
closeJButton.removeActionListener(oldListeners[i]);
}
this.closeJButton.addActionListener(l);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JButton closeJButton;
jfreerails.client.view.TrainScheduleJPanel newTrainScheduleJPanel1;
javax.swing.JButton nextJButton;
javax.swing.JButton previousJButton;
jfreerails.client.view.TrainDescriptionJPanel trainDetailsJPanel1;
javax.swing.JButton trainListJButton;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
display
initComponents/**
itemAdded
itemRemoved
listUpdated
nextJButtonActionPerformed
previousJButtonActionPerformed
setCancelButtonActionListener/**
setTrainDetailsButtonActionListener
setup
jfreerails.client.view.TrainListCellRenderer
Javadoc:
/** * This JPanel displays an engine and a number of wagons. * * @author Luke Lindsay */
Source code:
/**
* This JPanel displays an engine and a number of wagons.
*
* @author Luke Lindsay
*/
public class TrainListCellRenderer extends JPanel implements View, ListCellRenderer,
WorldListListener {
private static final long serialVersionUID = 3546076964969591093L;
private ReadOnlyWorld w;
private RenderersRoot vl;
private int trainNumber = -1;
private int scheduleOrderNumber;
private int scheduleID = -1;
private int height = 100;
private FreerailsPrincipal principal;
private Image[] images = new Image[0];
/**
* Whether this JPanel should one of the trains orders from the schedule
* instead of the trains current formation.
*/
private boolean showingOrder = false;
/**
* If true, the train is drawn in the center to the JPanel; if false, the
* train is drawn left aligned.
*/
private boolean centerTrain = false;
private int trainWidth = 0;
private boolean selected = false;
private final Color backgroundColor = (java.awt.Color) javax.swing.UIManager.getDefaults().get(
"List.background");
private final Color selectedColor = (java.awt.Color) javax.swing.UIManager.getDefaults().get(
"List.selectionBackground");
private final Color selectedColorNotFocused = Color.LIGHT_GRAY;
public TrainListCellRenderer() {
this.setOpaque(false);
}
public TrainListCellRenderer(ModelRoot mr, RenderersRoot vl) {
setup(mr, vl, null);
this.setBackground(backgroundColor);
}
public void setCenterTrain(boolean b) {
this.centerTrain = b;
}
public void display(int newTrainNumber) {
showingOrder = false;
this.trainNumber = newTrainNumber;
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS, trainNumber);
display(train.getEngineType(), train.getConsist());
resetPreferredSize();
}
private void display(int engine, ImInts wagons){
images = new Image[1 + wagons.size()];
// images[0] = vl.getTrainImages().getSideOnEngineImage(
// train.getEngineType(), height);
String engineFilename = vl.getEngineImages(engine).sideOnFileName;
try {
images[0] = vl.getScaledImage(engineFilename, height);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException(engineFilename);
}
for (int i = 0; i < wagons.size(); i++) {
// images[i + 1] = vl.getTrainImages().getSideOnWagonImage(
// order.consist.get(i), height);
int wagonType = wagons.get(i);
String wagonFilename = vl.getWagonImages(wagonType).sideOnFileName;
try {
images[i + 1] = vl.getScaledImage(wagonFilename, height);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException(wagonFilename);
}
}
}
public void display(int newTrainNumber, int newScheduleOrderID) {
showingOrder = true;
this.trainNumber = newTrainNumber;
this.scheduleOrderNumber = newScheduleOrderID;
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS, trainNumber);
this.scheduleID = train.getScheduleID();
ImmutableSchedule s = (ImmutableSchedule) w.get(principal, KEY.TRAIN_SCHEDULES, scheduleID);
TrainOrdersModel order = s.getOrder(newScheduleOrderID);
// Set up the array of images.
if (null != order.consist) {
display(train.getEngineType(), order.consist);
} else {
images = new Image[0];
}
resetPreferredSize();
}
private void resetPreferredSize() {
int width = 0;
for (int i = 0; i < images.length; i++) {
width += images[i].getWidth(null);
}
this.trainWidth = width;
this.setPreferredSize(new Dimension(width, height));
}
public void setup(ModelRoot mr, RenderersRoot vl, Action closeAction) {
this.w = mr.getWorld();
this.vl = vl;
this.principal = mr.getPrincipal();
}
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
int trainID = NonNullElements.row2index(w, KEY.TRAINS, principal, index);
display(trainID);
selected = isSelected;
if (selected) {
if (list.isFocusOwner()) {
setBackground(selectedColor);
} else {
setBackground(selectedColorNotFocused);
}
} else {
setBackground(backgroundColor);
}
return this;
}
@Override
public int getHeight() {
return height;
}
public void setHeight(int i) {
height = i;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 0;
if (this.centerTrain) {
x = (this.getWidth() - this.trainWidth) / 2;
}
for (int i = 0; i < images.length; i++) {
g.drawImage(images[i], x, 0, null);
x += images[i].getWidth(null);
}
}
public void listUpdated(KEY key, int index, FreerailsPrincipal p) {
if (showingOrder) {
if (KEY.TRAIN_SCHEDULES == key && this.scheduleID == index) {
this.display(this.trainNumber, this.scheduleOrderNumber);
}
} else {
if (KEY.TRAINS == key && this.trainNumber == index) {
this.display(this.trainNumber);
}
}
}
public void itemAdded(KEY key, int index, FreerailsPrincipal p) {
}
public void itemRemoved(KEY key, int index, FreerailsPrincipal p) {
}
}
Methods:
MethodJavadoc
display
display
display
getHeight
getListCellRendererComponent
itemAdded
itemRemoved
listUpdated
paintComponent
resetPreferredSize
setCenterTrain
setHeight
setup
jfreerails.client.view.TrainListJPanel
Javadoc:
/** * JPanel that displays a list of trains, used for the train list window and the * train roster tab. * * @author Luke */
Source code:
/**
* JPanel that displays a list of trains, used for the train list window and the
* train roster tab.
*
* @author Luke
*/
public class TrainListJPanel extends javax.swing.JPanel implements View, ModelRootListener {
private static final long serialVersionUID = 3832905463863064626L;
private ReadOnlyWorld world;
private FreerailsPrincipal principal;
private int lastNumberOfTrains = -1;
private boolean rhsjTabPane = false; // if the train list is for the
// rhsjTabPane then use the original
// renderer, if not use the
// trainsummaryjpanel
/** Creates new form TrainListJPanel. */
public TrainListJPanel() {
initComponents();
}
public TrainListJPanel(boolean isInRHSJTabPane) {
this();
rhsjTabPane = isInRHSJTabPane;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
trainSummaryJPanel1 = new jfreerails.client.view.TrainSummaryJPanel();
closeJButton = new javax.swing.JButton();
showDetails = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
trainNumLabel = new javax.swing.JLabel();
trainHeadingLabel = new javax.swing.JLabel();
maintenanceLabel = new javax.swing.JLabel();
incomeLabel = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(510, 300));
closeJButton.setText("Close");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(closeJButton, gridBagConstraints);
showDetails.setText("Show details");
showDetails.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showDetailsActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(showDetails, gridBagConstraints);
jList1
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.setCellRenderer(trainSummaryJPanel1);
jList1.setDoubleBuffered(true);
jList1.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
jList1KeyPressed(evt);
}
});
jList1
.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(
javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jList1.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
jList1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jList1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
trainNumLabel.setText("Train Number");
trainNumLabel.setMaximumSize(new java.awt.Dimension(500, 500));
trainNumLabel.setPreferredSize(new java.awt.Dimension(100, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
add(trainNumLabel, gridBagConstraints);
trainHeadingLabel.setText("Headed For");
trainHeadingLabel.setPreferredSize(new java.awt.Dimension(100, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
add(trainHeadingLabel, gridBagConstraints);
maintenanceLabel.setText("Maintenance YTD");
maintenanceLabel.setPreferredSize(new java.awt.Dimension(100, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
add(maintenanceLabel, gridBagConstraints);
incomeLabel.setText("Income YTD");
incomeLabel.setPreferredSize(new java.awt.Dimension(100, 14));
add(incomeLabel, new java.awt.GridBagConstraints());
}// GEN-END:initComponents
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {// GEN-FIRST:event_jList1ValueChanged
// if a train is selected, enable the 'show details' button.
if (jList1.getSelectedIndex() != -1) {
this.showDetails.setEnabled(true);
} else {
this.showDetails.setEnabled(false);
}
}// GEN-LAST:event_jList1ValueChanged
private void showDetailsActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showDetailsActionPerformed
showTrainDetails.actionPerformed(evt);
}// GEN-LAST:event_showDetailsActionPerformed
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_jList1MouseClicked
// Add your handling code here:
if (evt.getClickCount() == 2) {
showTrainDetails.actionPerformed(null);
}
}// GEN-LAST:event_jList1MouseClicked
private void jList1KeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_jList1KeyPressed
// Add your handling code here:
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
showTrainDetails.actionPerformed(null);
}
}// GEN-LAST:event_jList1KeyPressed
public void setup(final ModelRoot mr, RenderersRoot vl,
Action closeAction) {
world = mr.getWorld();
trainSummaryJPanel1.setup(mr, vl, null);
if (rhsjTabPane) {
jList1.setModel(new World2ListModelAdapter(mr.getWorld(),
KEY.TRAINS, mr.getPrincipal()));
TrainListCellRenderer trainView = new TrainListCellRenderer(mr, vl);
jList1.setCellRenderer(trainView);
trainView.setHeight(trainViewHeight);
}
ActionListener[] oldListeners = closeJButton.getActionListeners();
for (int i = 0; i < oldListeners.length; i++) {
closeJButton.removeActionListener(oldListeners[i]);
}
closeJButton.addActionListener(closeAction);
ListSelectionListener[] old = jList1.getListSelectionListeners();
for(ListSelectionListener x : old){
jList1.removeListSelectionListener(x);
}
jList1.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int id = getSelectedTrainID();
mr.setProperty(ModelRoot.Property.SELECTED_TRAIN, id);
}
});
principal = mr.getPrincipal();
ModelRootImpl mri = (ModelRootImpl) mr;
mri.addPropertyChangeListener(this);
}
void setShowTrainDetailsActionListener(ActionListener l) {
showTrainDetails = l;
}
private ActionListener showTrainDetails = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
};
int getSelectedTrainID() {
/*
* Note, the selected index is not the train id since trains that have
* been removed are not shown on the list.
*/
int row = jList1.getSelectedIndex();
if (row == -1) {
return -1;
} else {
return NonNullElements.row2index(world, KEY.TRAINS, principal, row);
}
}
/** When the train list is shown on a tab we don't want the buttons. */
void removeButtons() {
this.removeAll();
java.awt.GridBagConstraints gridBagConstraints;
setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton closeJButton;
private javax.swing.JLabel incomeLabel;
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel maintenanceLabel;
private javax.swing.JButton showDetails;
private javax.swing.JLabel trainHeadingLabel;
private javax.swing.JLabel trainNumLabel;
private jfreerails.client.view.TrainSummaryJPanel trainSummaryJPanel1;
// End of variables declaration//GEN-END:variables
private int trainViewHeight = 50;
@Override
public void setVisible(boolean aFlag) {
if (aFlag && null != world) {
// jList1.setModel(new World2ListModelAdapter(world,
// KEY.TRAINS,principal));
}
super.setVisible(aFlag);
}
public void setTrainViewHeight(int trainViewHeight) {
this.trainViewHeight = trainViewHeight;
}
@Override
public void paint(Graphics g) {
if (null != world) {
NonNullElements trains = new NonNullElements(KEY.TRAINS, world,
principal);
int newNumberOfTrains = trains.size();
if (newNumberOfTrains != this.lastNumberOfTrains) {
jList1.setModel(new World2ListModelAdapter(world, KEY.TRAINS,
principal));
if (newNumberOfTrains > 0) {
jList1.setSelectedIndex(0);
}
lastNumberOfTrains = newNumberOfTrains;
}
}
super.paint(g);
}
@Override
public void propertyChange(ModelRoot.Property p, Object oldValue, Object newValue) {
if(ModelRoot.Property.SELECTED_TRAIN == p){
if(!newValue.equals(this.getSelectedTrainID())){
//update needed..
TrainModel train = (TrainModel) world.get(principal, KEY.TRAINS, (int) newValue);
this.jList1.setSelectedValue(train, true);
}
}
}
}
Methods:
MethodJavadoc
getSelectedTrainID
initComponents/**
jList1KeyPressed
jList1MouseClicked
jList1ValueChanged
paint
propertyChange
removeButtons/** When the train list is shown on a tab we don't want the buttons. */
setShowTrainDetailsActionListener
setTrainViewHeight/**
setVisible
setup
showDetailsActionPerformed
jfreerails.client.view.TrainOrderJPanel
Javadoc:
/** * ListCellRenderer that displays a train order. * * @author Luke Lindsay */
Source code:
/**
* ListCellRenderer that displays a train order.
*
* @author Luke Lindsay
*/
public class TrainOrderJPanel extends javax.swing.JPanel implements View,
ListCellRenderer {
private static final long serialVersionUID = 4051047466990319413L;
private jfreerails.world.top.ReadOnlyWorld w;
private FreerailsPrincipal principal;
private final ImageIcon gotoNow = new ImageIcon(TrainOrderJPanel.class
.getResource("/jfreerails/client/graphics/selected_arrow.png"));
private final ImageIcon gotoAfterPriorityOrders = new ImageIcon(
TrainOrderJPanel.class
.getResource("/jfreerails/client/graphics/deselected_arrow.png"));
private final ImageIcon dontGoto = null;
private final Color backgroundColor = (java.awt.Color) javax.swing.UIManager
.getDefaults().get("List.background");
private final Color selectedColor = (java.awt.Color) javax.swing.UIManager
.getDefaults().get("List.selectionBackground");
private final Color selectedColorNotFocused = Color.LIGHT_GRAY;
public TrainOrderJPanel() {
initComponents();
this.setBackground(backgroundColor);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
gotoIcon = new javax.swing.JLabel();
consistChangeJPanel = new TrainListCellRenderer();
noChangeJLabel = new javax.swing.JLabel();
stationNameJLabel = new javax.swing.JLabel();
ordersJLabel = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
gotoIcon.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/jfreerails/client/graphics/selected_arrow.png")));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
add(gotoIcon, gridBagConstraints);
consistChangeJPanel.setLayout(new java.awt.GridBagLayout());
noChangeJLabel.setText("No Change");
consistChangeJPanel.add(noChangeJLabel,
new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
add(consistChangeJPanel, gridBagConstraints);
stationNameJLabel.setText("Some Station");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
add(stationNameJLabel, gridBagConstraints);
ordersJLabel.setText("wait until full / don't wait");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.ipadx = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 5);
add(ordersJLabel, gridBagConstraints);
}// GEN-END:initComponents
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
this.w = mr.getWorld();
TrainListCellRenderer trainViewJPanel = (TrainListCellRenderer) consistChangeJPanel;
trainViewJPanel.setHeight(15);
trainViewJPanel.setup(mr, vl, null);
this.principal = mr.getPrincipal();
}
public java.awt.Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus) {
TrainOrdersListModel.TrainOrdersListElement trainOrders = (TrainOrdersListModel.TrainOrdersListElement) value;
// Set station name
int stationNumber = trainOrders.order.stationId;
StationModel station = (StationModel) w.get(principal,
KEY.STATIONS, stationNumber);
String stationName = station.getStationName();
this.stationNameJLabel.setText(stationName);
// Set wait until full
String waitUntilFull = trainOrders.order.waitUntilFull ? "Wait until full"
: "";
this.ordersJLabel.setText(waitUntilFull);
// Set selected
if (isSelected) {
if (list.isFocusOwner()) {
setBackground(selectedColor);
} else {
setBackground(selectedColorNotFocused);
}
} else {
setBackground(backgroundColor);
}
// Set goto status.
switch (trainOrders.gotoStatus) {
case TrainOrdersListModel.DONT_GOTO:
this.gotoIcon.setIcon(this.dontGoto);
break;
case TrainOrdersListModel.GOTO_AFTER_PRIORITY_ORDERS:
this.gotoIcon.setIcon(this.gotoAfterPriorityOrders);
break;
case TrainOrdersListModel.GOTO_NOW:
this.gotoIcon.setIcon(this.gotoNow);
break;
default:
throw new IllegalArgumentException(String
.valueOf(trainOrders.gotoStatus));
}
this.gotoIcon.setPreferredSize(new Dimension(20, 20));
// Set consist
TrainListCellRenderer trainViewJPanel = (TrainListCellRenderer) consistChangeJPanel;
trainViewJPanel.display(trainOrders.trainNumber, index);
// Show priority orders.
if (trainOrders.isPriorityOrder) {
// Write the station name in upper case
String s = this.stationNameJLabel.getText();
this.stationNameJLabel.setText(s + " (Priority Orders)");
}
// Check for 'No change'
if (null == trainOrders.order.consist) {
if (trainOrders.order.autoConsist) {
this.noChangeJLabel.setText("Select wagons automatically");
} else {
this.noChangeJLabel.setText("No Change");
}
} else {
this.noChangeJLabel.setText(null);
}
// Set the section title
// this.sectionTitleJLabel.setText("trainOrders.sectionTitle");
return this;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JPanel consistChangeJPanel;
javax.swing.JLabel gotoIcon;
javax.swing.JLabel noChangeJLabel;
javax.swing.JLabel ordersJLabel;
javax.swing.JLabel stationNameJLabel;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
getListCellRendererComponent
initComponents/**
setup
jfreerails.client.view.TrainOrdersListModel
Javadoc:
/** * AbstractListModel used by {@link TrainScheduleJPanel} to display the orders * making up a train schedule. * * @author Luke Lindsay */
Source code:
/**
* AbstractListModel used by {@link TrainScheduleJPanel} to display the orders
* making up a train schedule.
*
* @author Luke Lindsay
*/
public class TrainOrdersListModel extends AbstractListModel {
private static final long serialVersionUID = 3762537827703009847L;
private final int trainNumber;
private final ReadOnlyWorld w;
private final FreerailsPrincipal principal;
public static final int DONT_GOTO = 0;
public static final int GOTO_NOW = 1;
public static final int GOTO_AFTER_PRIORITY_ORDERS = 2;
/**
* This class holds the values that are needed by the ListCellRender.
* TrainOrdersListModel.getElementAt(int index) returns an instance of this
* class.
*/
public static class TrainOrdersListElement {
public final boolean isPriorityOrder;
public final int gotoStatus;
public final TrainOrdersModel order;
public final int trainNumber;
public TrainOrdersListElement(boolean isPriorityOrder, int gotoStatus,
TrainOrdersModel order, int trainNumber) {
this.isPriorityOrder = isPriorityOrder;
this.gotoStatus = gotoStatus;
this.order = order;
this.trainNumber = trainNumber;
}
}
public TrainOrdersListModel(ReadOnlyWorld w, int trainNumber,
FreerailsPrincipal p) {
this.trainNumber = trainNumber;
this.w = w;
this.principal = p;
assert (null != getSchedule());
}
public Object getElementAt(int index) {
Schedule s = getSchedule();
int gotoStatus;
if (s.getNextScheduledOrder() == index) {
if (s.hasPriorityOrders()) {
gotoStatus = GOTO_AFTER_PRIORITY_ORDERS;
} else {
gotoStatus = GOTO_NOW;
}
} else {
if (s.hasPriorityOrders() && 0 == index) {
// These orders are the priority orders.
gotoStatus = GOTO_NOW;
} else {
gotoStatus = DONT_GOTO;
}
}
boolean isPriorityOrders = 0 == index && s.hasPriorityOrders();
TrainOrdersModel order = getSchedule().getOrder(index);
return new TrainOrdersListElement(isPriorityOrders, gotoStatus, order,
trainNumber);
}
public int getSize() {
Schedule s = getSchedule();
int size = 0;
if (s != null) {
size = s.getNumOrders();
}
return size;
}
public void fireRefresh() {
super.fireContentsChanged(this, 0, getSize());
}
private Schedule getSchedule() {
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
trainNumber);
ImmutableSchedule sched = null;
if (train != null) {
sched = (ImmutableSchedule) w.get(principal, KEY.TRAIN_SCHEDULES, train
.getScheduleID());
}
return sched;
}
}
Methods:
MethodJavadoc
fireRefresh
getElementAt
getSchedule
getSize
jfreerails.client.view.TrainScheduleJPanel
Javadoc:
/** * This JPanel displays a train's schedule and provides controls that let you * edit it. * * @author Luke Lindsay */
Source code:
/**
* This JPanel displays a train's schedule and provides controls that let you
* edit it.
*
* @author Luke Lindsay
*/
public class TrainScheduleJPanel extends javax.swing.JPanel implements View,
WorldListListener {
private static final long serialVersionUID = 3762248626113884214L;
private static final Logger logger = Logger
.getLogger(TrainScheduleJPanel.class.getName());
private int trainNumber = -1;
private int scheduleID = -1;
private TrainOrdersListModel listModel;
private ModelRoot modelRoot;
private RenderersRoot vl;
public TrainScheduleJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
trainOrderJPanel1 = new jfreerails.client.view.TrainOrderJPanel();
editOrderJPopupMenu = new javax.swing.JPopupMenu();
gotoStationJMenuItem = new javax.swing.JMenuItem();
changeStation = new javax.swing.JMenuItem();
removeStationJMenuItem = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JSeparator();
addWagonJMenu = new javax.swing.JMenu();
removeWagonsJMenu = new javax.swing.JMenu();
removeLastJMenuItem = new javax.swing.JMenuItem();
removeAllJMenuItem = new javax.swing.JMenuItem();
changeConsistJMenu = new javax.swing.JMenu();
noChangeJMenuItem = new javax.swing.JMenuItem();
engineOnlyJMenuItem = new javax.swing.JMenuItem();
autoConsistJMenuItem = new javax.swing.JMenuItem();
waitJMenu = new javax.swing.JMenu();
dontWaitJMenuItem = new javax.swing.JMenuItem();
waitUntilFullJMenuItem = new javax.swing.JMenuItem();
jSeparator2 = new javax.swing.JSeparator();
pullUpJMenuItem = new javax.swing.JMenuItem();
pushDownJMenuItem = new javax.swing.JMenuItem();
selectStationJPanel1 = new jfreerails.client.view.SelectStationJPanel();
selectStationJPopupMenu = new javax.swing.JPopupMenu();
this.selectStationJPopupMenu.add(selectStationJPanel1);
addStationJButton = new javax.swing.JButton();
priorityOrdersJButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
orders = new javax.swing.JList();
gotoStationJMenuItem.setText("Goto station");
gotoStationJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
gotoStationJMenuItemActionPerformed(evt);
}
});
editOrderJPopupMenu.add(gotoStationJMenuItem);
changeStation.setText("Change Station");
changeStation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
changeStationActionPerformed(evt);
}
});
editOrderJPopupMenu.add(changeStation);
removeStationJMenuItem.setText("Remove station");
removeStationJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeStationJMenuItemActionPerformed(evt);
}
});
editOrderJPopupMenu.add(removeStationJMenuItem);
editOrderJPopupMenu.add(jSeparator1);
addWagonJMenu.setText("Add Wagon");
editOrderJPopupMenu.add(addWagonJMenu);
removeWagonsJMenu.setText("Remove wagon(s)");
removeLastJMenuItem.setText("Remove last");
removeLastJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeLastJMenuItemActionPerformed(evt);
}
});
removeWagonsJMenu.add(removeLastJMenuItem);
removeAllJMenuItem.setText("Remove all wagons");
removeAllJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeAllJMenuItemActionPerformed(evt);
}
});
removeWagonsJMenu.add(removeAllJMenuItem);
editOrderJPopupMenu.add(removeWagonsJMenu);
changeConsistJMenu.setText("Change consist to..");
noChangeJMenuItem.setText("'No change'");
noChangeJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
noChangeJMenuItemActionPerformed(evt);
}
});
changeConsistJMenu.add(noChangeJMenuItem);
engineOnlyJMenuItem.setText("Engine only");
engineOnlyJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
engineOnlyJMenuItemActionPerformed(evt);
}
});
changeConsistJMenu.add(engineOnlyJMenuItem);
autoConsistJMenuItem.setText("Choose wagons automatically");
autoConsistJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
autoConsistJMenuItemActionPerformed(evt);
}
});
changeConsistJMenu.add(autoConsistJMenuItem);
editOrderJPopupMenu.add(changeConsistJMenu);
waitJMenu.setText("Wait at station");
dontWaitJMenuItem.setText("Don't wait");
dontWaitJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dontWaitJMenuItemActionPerformed(evt);
}
});
waitJMenu.add(dontWaitJMenuItem);
waitUntilFullJMenuItem.setText("Wait until full");
waitUntilFullJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
waitUntilFullJMenuItemActionPerformed(evt);
}
});
waitJMenu.add(waitUntilFullJMenuItem);
editOrderJPopupMenu.add(waitJMenu);
editOrderJPopupMenu.add(jSeparator2);
pullUpJMenuItem.setText("Pull up");
pullUpJMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pullUpJMenuItemActionPerformed(evt);
}
});
editOrderJPopupMenu.add(pullUpJMenuItem);
pushDownJMenuItem.setText("Push down");
pushDownJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pushDownJMenuItemActionPerformed(evt);
}
});
editOrderJPopupMenu.add(pushDownJMenuItem);
setLayout(new java.awt.GridBagLayout());
setBorder(new javax.swing.border.TitledBorder("Schedule"));
addStationJButton.setText("Add Station");
addStationJButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addStationJButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(addStationJButton, gridBagConstraints);
priorityOrdersJButton.setText("Add Priority Orders");
priorityOrdersJButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
priorityOrdersJButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(priorityOrdersJButton, gridBagConstraints);
jScrollPane1.setPreferredSize(new java.awt.Dimension(280, 160));
orders
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
orders.setCellRenderer(trainOrderJPanel1);
orders.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
ordersKeyPressed(evt);
}
});
orders.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
ordersMouseClicked(evt);
}
});
jScrollPane1.setViewportView(orders);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
add(jScrollPane1, gridBagConstraints);
}// GEN-END:initComponents
private void ordersKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_ordersKeyPressed
switch (evt.getKeyCode()) {
case KeyEvent.VK_O: {
// Add priority orders
priorityOrdersJButtonActionPerformed(null);
break;
}
case KeyEvent.VK_N: {
// Add station
addStationJButtonActionPerformed(null);
break;
}
default: {
// do nothing.
}
}
int orderNumber = this.orders.getSelectedIndex();
if (orderNumber == -1) {
// No order is selected.
return;
}
switch (evt.getKeyCode()) {
case KeyEvent.VK_G: {
// Goto station.
gotoStationJMenuItemActionPerformed(null);
break;
}
case KeyEvent.VK_S: {
// Change station
showSelectStation(this.getSchedule(), orderNumber);
break;
}
case KeyEvent.VK_A: {
// Auto schedule
setAutoConsist();
break;
}
case KeyEvent.VK_C: {
// Change add wagon
break;
}
case KeyEvent.VK_DELETE: {
// Remove station
removeStationJMenuItemActionPerformed(null);
break;
}
case KeyEvent.VK_BACK_SPACE: {
// Remove last wagon
removeLastWagon();
break;
}
case KeyEvent.VK_W: {
// toggle wait until full
MutableSchedule s = getSchedule();
TrainOrdersModel order = s.getOrder(orderNumber);
setWaitUntilFull(!order.waitUntilFull);
break;
}
default: {
// do nothing.
}
}
listModel.fireRefresh();
}// GEN-LAST:event_ordersKeyPressed
private void autoConsistJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_autoConsistJMenuItemActionPerformed
setAutoConsist();
}// GEN-LAST:event_autoConsistJMenuItemActionPerformed
private void changeStationActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_changeStationActionPerformed
int orderNumber = this.orders.getSelectedIndex();
showSelectStation(this.getSchedule(), orderNumber);
}// GEN-LAST:event_changeStationActionPerformed
private void removeAllJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_removeAllJMenuItemActionPerformed
removeAllWagons();
}// GEN-LAST:event_removeAllJMenuItemActionPerformed
private void removeLastJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_removeLastJMenuItemActionPerformed
removeLastWagon();
}// GEN-LAST:event_removeLastJMenuItemActionPerformed
private void waitUntilFullJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_waitUntilFullJMenuItemActionPerformed
setWaitUntilFull(true);
}// GEN-LAST:event_waitUntilFullJMenuItemActionPerformed
private void dontWaitJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_dontWaitJMenuItemActionPerformed
setWaitUntilFull(false);
}// GEN-LAST:event_dontWaitJMenuItemActionPerformed
private void engineOnlyJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_engineOnlyJMenuItemActionPerformed
removeAllWagons();
}// GEN-LAST:event_engineOnlyJMenuItemActionPerformed
private void noChangeJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_noChangeJMenuItemActionPerformed
noChange();
}// GEN-LAST:event_noChangeJMenuItemActionPerformed
private void priorityOrdersJButtonActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_priorityOrdersJButtonActionPerformed
MutableSchedule s = getSchedule();
try {
s.setPriorityOrders(new TrainOrdersModel(getFirstStationID(), null,
false, false));// TODO fix bug
showSelectStation(s, Schedule.PRIORITY_ORDERS);
} catch (NoSuchElementException e) {
logger
.warning("No stations exist so can't add station to schedule!");
}
}// GEN-LAST:event_priorityOrdersJButtonActionPerformed
private void addStationJButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addStationJButtonActionPerformed
MutableSchedule s = getSchedule();
try {
int newOrderNumber = s.addOrder(new TrainOrdersModel(
getFirstStationID(), null, false, false)); // TODO fix bug
showSelectStation(s, newOrderNumber);
} catch (NoSuchElementException e) {
logger
.warning("No stations exist so can't add station to schedule!");
}
}// GEN-LAST:event_addStationJButtonActionPerformed
private void removeStationJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_removeStationJMenuItemActionPerformed
MutableSchedule s = getSchedule();
if(s.getNumOrders() ==0){
logger.warning("Can't remove orders since non exist!");
return;
}
int i = orders.getSelectedIndex();
if(s.getNumOrders() <= i){
logger.warning("Order #"+String.valueOf(i)+" does not exist!");
return;
}
s.removeOrder(i);
sendUpdateMove(s);
}// GEN-LAST:event_removeStationJMenuItemActionPerformed
private void gotoStationJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_gotoStationJMenuItemActionPerformed
MutableSchedule s = getSchedule();
int i = orders.getSelectedIndex();
s.setOrderToGoto(i);
sendUpdateMove(s);
}// GEN-LAST:event_gotoStationJMenuItemActionPerformed
private void pushDownJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pushDownJMenuItemActionPerformed
MutableSchedule s = getSchedule();
int i = orders.getSelectedIndex();
s.pushDown(i);
sendUpdateMove(s);
orders.setSelectedIndex(i + 1);
}// GEN-LAST:event_pushDownJMenuItemActionPerformed
private void ordersMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_ordersMouseClicked
int i = orders.getSelectedIndex();
MutableSchedule s = getSchedule();
if (i >= s.getNumOrders()) {
// The selected index does not exist!
// For some reason, the JList hasn't updated yet.
i = -1;
}
if (-1 != i && java.awt.event.MouseEvent.BUTTON3 == evt.getButton()) {
// If an element is select and the right button is pressed.
TrainOrdersModel order = s.getOrder(i);
pullUpJMenuItem.setEnabled(s.canPullUp(i));
pushDownJMenuItem.setEnabled(s.canPushDown(i));
gotoStationJMenuItem.setEnabled(s.canSetGotoStation(i));
removeWagonsJMenu.setEnabled(order.orderHasWagons());
waitJMenu.setEnabled(order.orderHasWagons());
addWagonJMenu.setEnabled(order.hasLessThanMaximumNumberOfWagons());
setupWagonsPopup();
this.editOrderJPopupMenu.show(evt.getComponent(), evt.getX(), evt
.getY());
}
}// GEN-LAST:event_ordersMouseClicked
private void pullUpJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pullUpJMenuItemActionPerformed
MutableSchedule s = getSchedule();
int i = orders.getSelectedIndex();
s.pullUp(i);
sendUpdateMove(s);
orders.setSelectedIndex(i - 1);
}// GEN-LAST:event_pullUpJMenuItemActionPerformed
public void setup(ModelRoot mr, RenderersRoot vl, Action al) {
trainOrderJPanel1.setup(mr, vl, null);
this.modelRoot = mr;
this.vl = vl;
// This actionListener is fired by the select station popup when a
// station is selected.
Action action = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent evt) {
sendUpdateMove(selectStationJPanel1.generateNewSchedule());
selectStationJPopupMenu.setVisible(false);
listModel.fireRefresh();
orders.requestFocus();
}
};
this.selectStationJPanel1.setup(mr, vl, action);
}
public void display(int newTrainNumber) {
this.trainNumber = newTrainNumber;
FreerailsPrincipal principal = modelRoot.getPrincipal();
ReadOnlyWorld w = modelRoot.getWorld();
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
newTrainNumber);
this.scheduleID = train.getScheduleID();
listModel = new TrainOrdersListModel(w, newTrainNumber, principal);
orders.setModel(listModel);
orders.setFixedCellWidth(250);
listModel.fireRefresh();
enableButtons();
}
private void enableButtons() {
MutableSchedule s = getSchedule();
addStationJButton.setEnabled(s.canAddOrder());
// Only one set of priority orders are allowed.
priorityOrdersJButton.setEnabled(!s.hasPriorityOrders());
}
private MutableSchedule getSchedule() {
FreerailsPrincipal principal = modelRoot.getPrincipal();
ReadOnlyWorld w = modelRoot.getWorld();
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
trainNumber);
ImmutableSchedule immutableSchedule = (ImmutableSchedule) w.get(
principal, KEY.TRAIN_SCHEDULES, train.getScheduleID());
return new MutableSchedule(immutableSchedule);
}
/**
* Since stations can be removed, we should not assume that station 0
* exists: this method returns the id of the first station that exists.
*
*/
private int getFirstStationID() {
NonNullElements stations = new NonNullElements(KEY.STATIONS, modelRoot
.getWorld(), modelRoot.getPrincipal());
if (stations.next()) {
return stations.getIndex();
}
throw new NoSuchElementException();
}
private void setupWagonsPopup() {
addWagonJMenu.removeAll(); // Remove existing menu items.
NonNullElements cargoTypes = new NonNullElements(SKEY.CARGO_TYPES,
modelRoot.getWorld());
while (cargoTypes.next()) {
final CargoType wagonType = (CargoType) cargoTypes.getElement();
JMenuItem wagonMenuItem = new JMenuItem();
final int wagonTypeNumber = cargoTypes.getIndex();
wagonMenuItem.setText(wagonType.getDisplayName());
Image image = vl.getWagonImages(wagonTypeNumber).getSideOnImage();
int height = image.getHeight(null);
int width = image.getWidth(null);
int scale = height / 10;
ImageIcon icon = new ImageIcon(image.getScaledInstance(width
/ scale, height / scale, Image.SCALE_FAST));
wagonMenuItem.setIcon(icon);
wagonMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
addWagon(wagonTypeNumber);
}
});
addWagonJMenu.add(wagonMenuItem);
}
}
private void noChange() {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
newOrders = new TrainOrdersModel(oldOrders.getStationID(), null, false,
false);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
private void setWaitUntilFull(boolean b) {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
// If auto-consist is set do nothing
if (oldOrders.autoConsist)
return;
// If no-change is set do nothing
if (oldOrders.consist == null)
return;
boolean autoConsist = false;
newOrders = new TrainOrdersModel(oldOrders.getStationID(),
oldOrders.consist, b, autoConsist);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
private void setAutoConsist() {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
newOrders = new TrainOrdersModel(oldOrders.getStationID(), null, false,
true);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
private void addWagon(int wagonTypeNumber) {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
int[] newConsist;
// The consist will be null if old orders were 'no change'.
if (null != oldOrders.consist) {
int oldLength = oldOrders.consist.size();
newConsist = new int[oldLength + 1];
// Copy existing wagons
for (int i = 0; i < oldLength; i++) {
newConsist[i] = oldOrders.consist.get(i);
}
// Then add specified wagon.
newConsist[oldLength] = wagonTypeNumber;
} else {
newConsist = new int[] { wagonTypeNumber };
}
newOrders = new TrainOrdersModel(oldOrders.getStationID(), new ImInts(
newConsist), oldOrders.getWaitUntilFull(), false);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
private void removeAllWagons() {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
newOrders = new TrainOrdersModel(oldOrders.getStationID(),
new ImInts(), false, false);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
private void removeLastWagon() {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
ImInts oldConsist = oldOrders.consist;
if( null == oldConsist){
//consist can be null if there is no
//scheduled change of wagons.
//Fixes freerails bug 1687677 and freerails2 bug 2014234
return;
}
int newLength = oldConsist.size() - 1;
if (newLength < 0) {
//No wagons to remove!
return;
}
ImInts newConsist = oldConsist.removeLast();
newOrders = new TrainOrdersModel(oldOrders.getStationID(), newConsist,
oldOrders.waitUntilFull, false);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
private void sendUpdateMove(MutableSchedule mutableSchedule) {
FreerailsPrincipal principal = modelRoot.getPrincipal();
ReadOnlyWorld w = modelRoot.getWorld();
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
this.trainNumber);
// int scheduleID = train.getScheduleID();
assert (scheduleID == train.getScheduleID());
ImmutableSchedule before = (ImmutableSchedule) w.get(
principal, KEY.TRAIN_SCHEDULES, scheduleID);
ImmutableSchedule after = mutableSchedule.toImmutableSchedule();
Move m = new ChangeTrainScheduleMove(scheduleID, before, after,
principal);
this.modelRoot.doMove(m);
}
public void listUpdated(KEY key, int index, FreerailsPrincipal p) {
if (KEY.TRAIN_SCHEDULES == key && this.scheduleID == index) {
listModel.fireRefresh();
enableButtons();
}
}
public void itemAdded(KEY key, int index, FreerailsPrincipal p) {
// do nothing.
}
public void itemRemoved(KEY key, int index, FreerailsPrincipal p) {
// do nothing.
}
/**
* Show the popup that lets the user select a station, called when a new
* scheduled stop is added and when an existing scheduled stop is changed.
*/
private void showSelectStation(MutableSchedule schedule, int orderNumber) {
selectStationJPanel1.display(schedule, orderNumber);
// Show the select station popup in the middle of the window.
Container topLevelAncestor = this.getTopLevelAncestor();
Dimension d = topLevelAncestor.getSize();
Dimension d2 = selectStationJPopupMenu.getPreferredSize();
int x = Math.max((d.width - d2.width) / 2, 0);
int y = Math.max((d.height - d2.height) / 2, 0);
selectStationJPopupMenu.show(topLevelAncestor, x, y);
selectStationJPanel1.requestFocus();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JButton addStationJButton;
javax.swing.JMenu addWagonJMenu;
javax.swing.JMenuItem autoConsistJMenuItem;
javax.swing.JMenu changeConsistJMenu;
javax.swing.JMenuItem changeStation;
javax.swing.JMenuItem dontWaitJMenuItem;
javax.swing.JPopupMenu editOrderJPopupMenu;
javax.swing.JMenuItem engineOnlyJMenuItem;
javax.swing.JMenuItem gotoStationJMenuItem;
javax.swing.JScrollPane jScrollPane1;
javax.swing.JSeparator jSeparator1;
javax.swing.JSeparator jSeparator2;
javax.swing.JMenuItem noChangeJMenuItem;
javax.swing.JList orders;
javax.swing.JButton priorityOrdersJButton;
javax.swing.JMenuItem pullUpJMenuItem;
javax.swing.JMenuItem pushDownJMenuItem;
javax.swing.JMenuItem removeAllJMenuItem;
javax.swing.JMenuItem removeLastJMenuItem;
javax.swing.JMenuItem removeStationJMenuItem;
javax.swing.JMenu removeWagonsJMenu;
jfreerails.client.view.SelectStationJPanel selectStationJPanel1;
javax.swing.JPopupMenu selectStationJPopupMenu;
jfreerails.client.view.TrainOrderJPanel trainOrderJPanel1;
javax.swing.JMenu waitJMenu;
javax.swing.JMenuItem waitUntilFullJMenuItem;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
addStationJButtonActionPerformed
addWagon
autoConsistJMenuItemActionPerformed
changeStationActionPerformed/**
display
dontWaitJMenuItemActionPerformed
enableButtons
engineOnlyJMenuItemActionPerformed
getFirstStationID/**
getSchedule
gotoStationJMenuItemActionPerformed
initComponents/**
itemAdded
itemRemoved
listUpdated
noChange
noChangeJMenuItemActionPerformed
ordersKeyPressed
ordersMouseClicked
priorityOrdersJButtonActionPerformed
pullUpJMenuItemActionPerformed/**
pushDownJMenuItemActionPerformed
removeAllJMenuItemActionPerformed
removeAllWagons
removeLastJMenuItemActionPerformed
removeLastWagon
removeStationJMenuItemActionPerformed
sendUpdateMove
setAutoConsist
setWaitUntilFull
setup
setupWagonsPopup
showSelectStation/**
waitUntilFullJMenuItemActionPerformed
jfreerails.client.view.TrainSummaryJPanel
Javadoc:
/** * * @author cphillips */
Source code:
/**
*
* @author cphillips
*/
public class TrainSummaryJPanel extends javax.swing.JPanel implements
ListCellRenderer, View {
private static final long serialVersionUID = 4121133628006020919L;
private jfreerails.world.top.ReadOnlyWorld w;
private FreerailsPrincipal principal;
private final Color backgroundColor = (java.awt.Color) javax.swing.UIManager
.getDefaults().get("List.background");
private final Color selectedColor = (java.awt.Color) javax.swing.UIManager
.getDefaults().get("List.selectionBackground");
private final Color selectedColorNotFocused = Color.LIGHT_GRAY;
private TrainListCellRenderer trainListCellRenderer1;
/** Creates new form TrainSummaryJPanel */
public TrainSummaryJPanel() {
initComponents();
}
public void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
this.principal = modelRoot.getPrincipal();
this.w = modelRoot.getWorld();
trainListCellRenderer1 = new TrainListCellRenderer(modelRoot, vl);
trainListCellRenderer1.setHeight(15);
}
private String findStationName(int trainNum) {
TrainOrdersModel orders = null;
TrainOrdersListModel ordersList = new TrainOrdersListModel(w, trainNum,
principal);
for (int i = 0; i < ordersList.getSize(); ++i) {
TrainOrdersListElement element = (TrainOrdersListElement) ordersList
.getElementAt(i);
if (element.gotoStatus == TrainOrdersListModel.GOTO_NOW) {
orders = element.order;
break;
}
}
StationModel station = (StationModel) w.get(principal, KEY.STATIONS, orders
.getStationID());
return station.getStationName();
}
private String findTrainIncome(int trainNum) {
IncomeStatementGenerator income = new IncomeStatementGenerator(w,
principal);
Money m = income.calTrainRevenue(trainNum);
return "$" + m.toString();
}
public java.awt.Component getListCellRendererComponent(
javax.swing.JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
int trainID = NonNullElements
.row2index(w, KEY.TRAINS, principal, index);
trainNumLabel.setText("#" + (trainID + 1));
headingLabel.setText(findStationName(trainID));
trainMaintenanceCostLabel.setText(findMaintenanceCost());
trainIncomeLabel.setText(findTrainIncome(trainID));
java.awt.GridBagConstraints gridBagConstraints;
trainListCellRenderer1.setOpaque(true);
trainListCellRenderer1.setCenterTrain(false);
trainListCellRenderer1.display(trainID);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(3, 0, 3, 0);
add(trainListCellRenderer1, gridBagConstraints);
if (isSelected) {
if (list.isFocusOwner()) {
setBackground(selectedColor);
trainListCellRenderer1.setBackground(selectedColor);
} else {
setBackground(selectedColorNotFocused);
trainListCellRenderer1.setBackground(selectedColorNotFocused);
}
} else {
setBackground(backgroundColor);
trainListCellRenderer1.setBackground(backgroundColor);
}
// Set selected
return this;
}
private String findMaintenanceCost() {
GameTime time = w.currentTime();
GameCalendar gameCalendar = (GameCalendar) w.get(ITEM.CALENDAR);
double month = gameCalendar.getMonth(time.getTicks());
long cost = (long) (month / 12 * 5000);
Money m = new Money(cost);
return "$" + m.toString();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
trainNumLabel = new javax.swing.JLabel();
headingLabel = new javax.swing.JLabel();
trainMaintenanceCostLabel = new javax.swing.JLabel();
trainIncomeLabel = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(500, 50));
trainNumLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
trainNumLabel.setText("jLabel1");
trainNumLabel
.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
trainNumLabel.setPreferredSize(new java.awt.Dimension(100, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
add(trainNumLabel, gridBagConstraints);
headingLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
headingLabel.setText("jLabel2");
headingLabel
.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
headingLabel.setPreferredSize(new java.awt.Dimension(100, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10);
add(headingLabel, gridBagConstraints);
trainMaintenanceCostLabel
.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
trainMaintenanceCostLabel.setText("jLabel3");
trainMaintenanceCostLabel.setMaximumSize(getMaximumSize());
trainMaintenanceCostLabel.setPreferredSize(new java.awt.Dimension(100,
25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10);
add(trainMaintenanceCostLabel, gridBagConstraints);
trainIncomeLabel
.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
trainIncomeLabel.setText("jLabel1");
trainIncomeLabel.setPreferredSize(new java.awt.Dimension(100, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
add(trainIncomeLabel, gridBagConstraints);
}// GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel headingLabel;
private javax.swing.JLabel trainIncomeLabel;
private javax.swing.JLabel trainMaintenanceCostLabel;
private javax.swing.JLabel trainNumLabel;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
findMaintenanceCost
findStationName
findTrainIncome
getListCellRendererComponent
initComponents/**
setup
jfreerails.client.view.View
Javadoc:
/** * Defines a standard method to initiate GUI components that need access to the * ModelRoot. * * @author Luke * */
Source code:
/**
* Defines a standard method to initiate GUI components that need access to the
* ModelRoot.
*
* @author Luke
*
*/
public interface View {
void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction);
}
Methods:
MethodJavadoc
setup
jfreerails.client.view.World2ListModelAdapter
Javadoc:
/** * Converts the interface of a list on the world object to a ListModel interface * that can be used by JLists. Currently, change notification is <b>not</b> * implemented (null elements are skipped). * * @author Luke * */
Source code:
/**
* Converts the interface of a list on the world object to a ListModel interface
* that can be used by JLists. Currently, change notification is <b>not</b>
* implemented (null elements are skipped).
*
* @author Luke
*
*/
public class World2ListModelAdapter implements ListModel {
private final ReadOnlyWorld w;
private final NonNullElements elements;
public World2ListModelAdapter(ReadOnlyWorld world, SKEY key) {
this.w = world;
if (null == key)
throw new NullPointerException();
if (null == w)
throw new NullPointerException();
elements = new NonNullElements(key, world);
}
public World2ListModelAdapter(ReadOnlyWorld world, KEY key,
FreerailsPrincipal p) {
this.w = world;
if (null == key)
throw new NullPointerException();
if (null == p)
throw new NullPointerException();
if (null == w)
throw new NullPointerException();
// Check that the principal exists.
if (!world.isPlayer(p))
throw new IllegalArgumentException(p.getName());
elements = new NonNullElements(key, world, p);
}
public int getSize() {
return elements.size();
}
public Object getElementAt(int i) {
elements.gotoRow(i);
return elements.getElement();
}
public void addListDataListener(ListDataListener arg0) {
// TODO Auto-generated method stub
}
public void removeListDataListener(ListDataListener arg0) {
// TODO Auto-generated method stub
}
}
Methods:
MethodJavadoc
addListDataListener
getElementAt
getSize
removeListDataListener
jfreerails.controller.AddStationPreMove
Javadoc:
/** * Generates a move that adds or upgrades a station. * * @author Luke * */
Source code:
/**
* Generates a move that adds or upgrades a station.
*
* @author Luke
*
*/
public class AddStationPreMove implements PreMove {
private static final long serialVersionUID = 3258131349411148085L;
private final ImPoint p;
private final int ruleNumber;
private final FreerailsPrincipal principal;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof AddStationPreMove))
return false;
final AddStationPreMove addStationPreMove = (AddStationPreMove) o;
if (ruleNumber != addStationPreMove.ruleNumber)
return false;
if (!p.equals(addStationPreMove.p))
return false;
if (!principal.equals(addStationPreMove.principal))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = p.hashCode();
result = 29 * result + ruleNumber;
result = 29 * result + principal.hashCode();
return result;
}
private AddStationPreMove(ImPoint p, int trackRule,
FreerailsPrincipal principal) {
this.p = p;
this.ruleNumber = trackRule;
this.principal = principal;
}
public static AddStationPreMove newStation(ImPoint p, int trackRule,
FreerailsPrincipal principal) {
return new AddStationPreMove(p, trackRule, principal);
}
public static AddStationPreMove upgradeStation(ImPoint p, int trackRule,
FreerailsPrincipal principal) {
return new AddStationPreMove(p, trackRule, principal);
}
public Move generateMove(ReadOnlyWorld world) {
TrackMoveTransactionsGenerator transactionsGenerator = new TrackMoveTransactionsGenerator(
world, principal);
FreerailsTile oldTile = (FreerailsTile) world.getTile(p.x, p.y);
String cityName;
String stationName;
FreerailsTile ft = (FreerailsTile)world.getTile(p.x, p.y);
TrackPiece before = ft.getTrackPiece();
TrackRule trackRule = (TrackRule) world.get(SKEY.TRACK_RULES,
this.ruleNumber);
int owner = ChangeTrackPieceCompositeMove.getOwner(principal, world);
TrackPiece after = new TrackPieceImpl(before.getTrackConfiguration(),
trackRule, owner, ruleNumber);
ChangeTrackPieceMove upgradeTrackMove = new ChangeTrackPieceMove(
before, after, p);
CompositeMove move;
if (!oldTile.getTrackPiece().getTrackRule().isStation()) {
// There isn't already a station here, we need to pick a name and
// add an entry
// to the station list.
CalcNearestCity cNC = new CalcNearestCity(world, p.x, p.y);
try {
cityName = cNC.findNearestCity();
VerifyStationName vSN = new VerifyStationName(world, cityName);
stationName = vSN.getName();
} catch (NoSuchElementException e) {
// there are no cities, this should never happen during a proper
// game. However
// some of the unit tests create stations when there are no
// cities.
stationName = "Central Station #"
+ world.size(principal, KEY.STATIONS);
}
// check the terrain to see if we can build a station on it...
move = AddStationMove.generateMove(world, stationName, p,
upgradeTrackMove, principal);
move = addSupplyAndDemand(move, world);
move = transactionsGenerator.addTransactions(move);
} else {
// Upgrade an existing station.
move = AddStationMove.upgradeStation(upgradeTrackMove);
}
return move;
}
private CompositeMove addSupplyAndDemand(CompositeMove m, ReadOnlyWorld w) {
ImList<Move> moves2 = m.getMoves();
Move[] moves = new Move[moves2.size()];
for (int i = 0; i < moves2.size(); i++) {
moves[i] = moves2.get(i);
}
for (int i = 0; i < moves.length; i++) {
if (moves[i] instanceof AddItemToListMove) {
AddItemToListMove move = (AddItemToListMove) moves[i];
if (move.getKey().equals(KEY.STATIONS)) {
StationModel station = (StationModel) move.getAfter();
CalcCargoSupplyRateAtStation supplyRate;
supplyRate = new CalcCargoSupplyRateAtStation(w, station.x,
station.y, ruleNumber);
StationModel stationAfter = supplyRate
.calculations(station);
moves[i] = new AddItemToListMove(move.getKey(), move
.getIndex(), stationAfter, move.getPrincipal());
}
}
}
return new CompositeMove(moves);
}
}
Methods:
MethodJavadoc
addSupplyAndDemand
generateMove
newStation
upgradeStation
jfreerails.controller.AddTrainPreMove
Javadoc:
/** * @author Luke * */
Source code:
/**
* @author Luke
*
*/
public class AddTrainPreMove implements PreMove {
private static final long serialVersionUID = 4050201951105069624L;
private final int engineTypeId;
private final ImInts wagons;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof AddTrainPreMove)) {
return false;
}
final AddTrainPreMove addTrainPreMove = (AddTrainPreMove) o;
if (engineTypeId != addTrainPreMove.engineTypeId) {
return false;
}
if (!point.equals(addTrainPreMove.point)) {
return false;
}
if (!principal.equals(addTrainPreMove.principal)) {
return false;
}
if (!schedule.equals(addTrainPreMove.schedule)) {
return false;
}
if (!wagons.equals(addTrainPreMove.wagons)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result;
result = engineTypeId;
result = 29 * result + point.hashCode();
result = 29 * result + principal.hashCode();
result = 29 * result + schedule.hashCode();
return result;
}
private final ImPoint point;
private final FreerailsPrincipal principal;
private final ImmutableSchedule schedule;
public AddTrainPreMove(int e, ImInts wags, ImPoint p,
FreerailsPrincipal fp, ImmutableSchedule s) {
engineTypeId = e;
wagons = wags;
point = p;
principal = fp;
schedule = s;
if (null == wags) {
throw new NullPointerException();
}
if (null == p) {
throw new NullPointerException();
}
if (null == fp) {
throw new NullPointerException();
}
if (null == s) {
throw new NullPointerException();
}
}
PathOnTiles initPositionStep1(ReadOnlyWorld w) {
PositionOnTrack[] pp = FlatTrackExplorer.getPossiblePositions(w, point);
FlatTrackExplorer fte = new FlatTrackExplorer(w, pp[0]);
List<Step> steps = new ArrayList<Step>();
int length = calTrainLength();
int distanceTravelled = 0;
PositionOnTrack p = new PositionOnTrack();
while (distanceTravelled < length) {
fte.nextEdge();
fte.moveForward();
p.setValuesFromInt(fte.getPosition());
Step v = p.cameFrom();
distanceTravelled += v.getLength();
steps.add(v);
}
return new PathOnTiles(point, steps);
}
private int calTrainLength() {
TrainModel train = new TrainModel(engineTypeId, wagons, 0);
int length = train.getLength();
return length;
}
TrainMotion initPositionStep2(PathOnTiles path) {
// TODO fix code.
TrainMotion tm = new TrainMotion(path, path.steps(), calTrainLength(),
ConstAcc.STOPPED);
return tm;
}
/**
* Generates a move that does the following.
* <ol>
* <li>Adds the train</li>
* <li>Adds a cargo bundle to represent the cargo the train is
* carrying</li>
* <li>Adds a schedule for the train</li>
* <li>Adds transaction to pay for the train</li>
* <li>Init. the trains position and motion</li>
* </ol>
*
*
*/
public Move generateMove(ReadOnlyWorld w) {
// Add cargo bundle.
int bundleId = w.size(principal, KEY.CARGO_BUNDLES);
ImmutableCargoBundle cargo = ImmutableCargoBundle.EMPTY_BUNDLE;
AddItemToListMove addCargoBundle = new AddItemToListMove(
KEY.CARGO_BUNDLES, bundleId, cargo, principal);
// Add schedule
for (int i = 0; i < schedule.getNumOrders(); i++) {
TrainOrdersModel order = schedule.getOrder(i);
if (!w.boundsContain(principal, KEY.STATIONS, order.stationId)) {
throw new ArrayIndexOutOfBoundsException(String.format("%d", order.stationId));
}
}
int scheduleId = w.size(principal, KEY.TRAIN_SCHEDULES);
AddItemToListMove addSchedule = new AddItemToListMove(
KEY.TRAIN_SCHEDULES, scheduleId, schedule, principal);
// Add train to train list.
TrainModel train = new TrainModel(engineTypeId, wagons, scheduleId,
bundleId);
int trainId = w.size(principal, KEY.TRAINS);
AddItemToListMove addTrain = new AddItemToListMove(KEY.TRAINS, trainId,
train, principal);
// Pay for train.
int quantity = 1;
/* Determine the price of the train. */
EngineType engineType = (EngineType) w.get(SKEY.ENGINE_TYPES,
engineTypeId);
Money price = engineType.getPrice();
Transaction transaction = new AddItemTransaction(
Transaction.Category.TRAIN, engineTypeId, quantity, new Money(
-price.getAmount()));
AddTransactionMove transactionMove = new AddTransactionMove(principal,
transaction);
// Setup and add train position.
PathOnTiles path = initPositionStep1(w);
TrainMotion motion = initPositionStep2(path);
Move addPosition = new AddActiveEntityMove(motion, trainId,
principal);
return new CompositeMove(addCargoBundle, addSchedule, addTrain,
transactionMove, addPosition);
}
}
Methods:
MethodJavadoc
calTrainLength
generateMove/**
initPositionStep1
initPositionStep2
jfreerails.controller.BalanceSheetGenerator
Javadoc:
/** * Generates the balance sheet - note, its fields are read using reflection so * don't change their names. * * @author Luke * */
Source code:
/**
* Generates the balance sheet - note, its fields are read using reflection so
* don't change their names.
*
* @author Luke
*
*/
public class BalanceSheetGenerator {
GameTime from;
GameTime to;
final ReadOnlyWorld w;
final FreerailsPrincipal principal;
private GameCalendar cal;
public String year;
public Stats total;
public Stats ytd;
public BalanceSheetGenerator(ReadOnlyWorld w, FreerailsPrincipal principal) {
this.w = w;
this.principal = principal;
cal = (GameCalendar) w.get(ITEM.CALENDAR);
// Calculate totals
GameTime time = w.currentTime();
final int startyear = cal.getYear(time.getTicks());
year = String.valueOf(startyear);
GameTime startOfYear = new GameTime(cal.getTicks(startyear));
GameTime[] totalTimeInterval = new GameTime[] { GameTime.BIG_BANG,
GameTime.END_OF_THE_WORLD };
total = new Stats(w, principal, totalTimeInterval);
GameTime[] ytdTimeInterval = new GameTime[] { startOfYear,
GameTime.END_OF_THE_WORLD };
ytd = new Stats(w, principal, ytdTimeInterval);
}
public static Money calTrackTotal(Transaction.Category category,
ReadOnlyWorld w, FreerailsPrincipal principal, GameTime startTime) {
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, principal);
aggregator.setCategory(TRACK);
long amount = 0;
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
long trackValue = trackRule.getPrice().getAmount();
GameTime[] times = new GameTime[] { startTime,
GameTime.END_OF_THE_WORLD };
aggregator.setType(i);
aggregator.setTimes(times);
ItemsTransactionAggregator.QuantitiesAndValues qnv = aggregator
.calculateQuantitiesAndValues();
int quantity = qnv.quantities[0];
amount += trackValue * quantity
/ TrackConfiguration.LENGTH_OF_STRAIGHT_TRACK_PIECE;
}
return new Money(amount);
}
public static class Stats {
public Stats(ReadOnlyWorld w, FreerailsPrincipal principal, final GameTime[] totalTimeInterval){
TransactionAggregator operatingFundsAggregator = new TransactionAggregator(w,
principal) {
@Override
protected boolean condition(int i) {
int transactionTicks = w.getTransactionTimeStamp(
principal, i).getTicks();
int from = totalTimeInterval[0].getTicks();
int to = totalTimeInterval[1].getTicks();
return transactionTicks >= from && transactionTicks <=to;
}
};
operatingFunds= operatingFundsAggregator.calculateValue();
track = calTrackTotal(TRACK, w, principal, totalTimeInterval[0]);
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, principal);
aggregator.setTimes(totalTimeInterval);
aggregator.setCategory(STATIONS);
stations = aggregator.calculateValue();
aggregator.setCategory(TRAIN);
rollingStock = aggregator.calculateValue();
aggregator.setCategory(INDUSTRIES);
industries = aggregator.calculateValue();
aggregator.setCategory(BOND);
loans = aggregator.calculateValue();
aggregator.setCategory(ISSUE_STOCK);
equity= aggregator.calculateValue();
//If we don't initialize this variable
//we get a NPE when we don't own any stock in others RRs
otherRrStock = new Money(0);
int thisPlayerId = w.getID(principal);
StockPrice[] stockPrices = (new StockPriceCalculator(w)).calculate();
for (int playerId = 0; playerId < w.getNumberOfPlayers(); playerId++) {
aggregator.setCategory(TRANSFER_STOCK);
aggregator.setType(thisPlayerId);
int quantity = aggregator.calculateQuantity();
if (playerId == thisPlayerId) {
treasuryStock = new Money(quantity
* stockPrices[playerId].currentPrice.getAmount());
} else {
otherRrStock = new Money(quantity
* stockPrices[playerId].currentPrice.getAmount()
+ otherRrStock.getAmount());
}
}
calProfit();
}
public Money operatingFunds;
public Money track;
public Money stations;
public Money rollingStock;
public Money industries;
public Money loans;
public Money equity;
public Money treasuryStock;
public Money otherRrStock;
public Money profit;
private void calProfit(){
long profitValue = operatingFunds.getAmount() + track.getAmount()
+ stations.getAmount() + rollingStock.getAmount()
+ industries.getAmount() + loans.getAmount()
+ equity.getAmount() + treasuryStock.getAmount()
+ otherRrStock.getAmount();
profit= new Money(profitValue);
}
}
}
Methods:
MethodJavadoc
calTrackTotal
jfreerails.controller.BuildTrackExplorer
Javadoc:
/** * GraphExplorer that explorers possible track placements, the ints it returns * are encoded PositionOnTrack objects. * * @author Luke * */
Source code:
/**
* GraphExplorer that explorers possible track placements, the ints it returns
* are encoded PositionOnTrack objects.
*
* @author Luke
*
*/
public class BuildTrackExplorer implements GraphExplorer {
private static final TrackConfiguration TILE_CENTER = TrackConfiguration
.getFlatInstance("000010000");
private boolean beforeFirst = true;
final PositionOnTrack currentBranch = PositionOnTrack.createComingFrom(0,
0, Step.NORTH);
final private PositionOnTrack currentPosition = PositionOnTrack
.createComingFrom(0, 0, Step.NORTH);
private int directionInt = 0;
private final ImPoint target;
private BuildTrackStrategy buildTrackStrategy;
private boolean usingExistingTrack = false;
private final ReadOnlyWorld world;
private final FreerailsPrincipal principal;
public BuildTrackExplorer(ReadOnlyWorld w, FreerailsPrincipal principal) {
this(w, principal, null, new ImPoint(0, 0));
}
public BuildTrackExplorer(ReadOnlyWorld w, FreerailsPrincipal principal,
ImPoint start, ImPoint target) {
world = w;
this.principal = principal;
PositionOnTrack pos;
if (null == start) {
pos = new PositionOnTrack();
} else {
pos = PositionOnTrack
.createComingFrom(start.x, start.y, Step.NORTH);
}
currentPosition.setValuesFromInt(pos.toInt());
directionInt = 0;
this.target = target;
buildTrackStrategy = BuildTrackStrategy.getDefault(w);
}
/**
* <p>
* Tests whether we can build track in the direction specified by
* m_direction.
* </p>
*
* <p>
* If we enter a tile from a given direction, the tiles we can build track
* to depend on the following. (1) The terrain type of the surrounding tiles -
* track can only be built on certain terrain types. (2) The direction we
* entered the current tile from. (3) Any existing track on the current tile -
* limits possible track configurations. (4) The terrain type of the current
* tile - terrain type determines which track types and hence which track
* configurations can be built.
* </p>
*
*/
private boolean canBuildTrack() {
// Check that we are not doubling back on ourselves.
Step opposite2current = currentPosition.cameFrom().getOpposite();
int currentX = currentPosition.getX();
int currentY = currentPosition.getY();
int directionWeCameFrom = opposite2current.getID();
int directionWeCameFromPlus = (directionWeCameFrom + 1) % 8;
int directionWeCameFromMinus = (directionWeCameFrom + 7) % 8;
if (directionInt == directionWeCameFrom
|| directionInt == directionWeCameFromPlus
|| directionInt == directionWeCameFromMinus) {
return false;
}
// Check that we are not going off the map.
Step directionOfNextTile = Step.getInstance(directionInt);
int newX = currentX + directionOfNextTile.getDx();
int newY = currentY + directionOfNextTile.getDy();
if (!world.boundsContain(newX, newY)) {
return false;
}
TrackRule rule4nextTile;
TrackRule rule4lastTile;
// Determine the track rule for the next tile.
final FreerailsTile nextTile = (FreerailsTile) world.getTile(newX,
newY);
// Check there is not another players track at nextTile.
if (nextTile.hasTrack()) {
if (nextTile.getTrackPiece().getOwnerID() != world.getID(principal)) {
return false;
}
}
rule4nextTile = getAppropriateTrackRule(newX, newY);
if (null == rule4nextTile) {
return false; // We can't build track on the tile.
}
rule4lastTile = getAppropriateTrackRule(currentX, currentY);
if (null == rule4lastTile) {
return false; // We can't build track on the tile.
}
// Determine the track rule for the current tile.
FreerailsTile currentTile = (FreerailsTile) world.getTile(currentX,
currentY);
// Check for illegal track configurations.
final TrackConfiguration trackAlreadyPresent1 = currentTile
.getTrackPiece().getTrackConfiguration();
final TrackConfiguration trackAlreadyPresent2 = nextTile
.getTrackPiece().getTrackConfiguration();
TrackConfiguration fromConfig = trackAlreadyPresent1;
fromConfig = TrackConfiguration.add(fromConfig, opposite2current);
fromConfig = TrackConfiguration.add(fromConfig, TILE_CENTER);
Step goingTo = Step.getInstance(directionInt);
fromConfig = TrackConfiguration.add(fromConfig, goingTo);
if (!rule4lastTile.trackPieceIsLegal(fromConfig)) {
return false;
}
// Check for diagonal conflicts.
if (directionOfNextTile.isDiagonal()) {
int x2check = currentX;
int y2check = currentY + directionOfNextTile.deltaY;
// We did a bounds check above.
assert (world.boundsContain(x2check, y2check));
FreerailsTile tile2Check = (FreerailsTile) world.getTile(x2check,
y2check);
TrackConfiguration config2check = tile2Check
.getTrackPiece().getTrackConfiguration();
Step vector2check = Step.getInstance(directionOfNextTile.deltaX,
-directionOfNextTile.deltaY);
if (config2check.contains(vector2check)) {
// then we have a diagonal conflict.
return false;
}
}
// Check for illegal track configurations on the tile we are entering.
TrackConfiguration fromConfig2 = trackAlreadyPresent2;
fromConfig2 = TrackConfiguration.add(fromConfig2, TILE_CENTER);
Step goingBack = Step.getInstance(directionInt).getOpposite();
fromConfig2 = TrackConfiguration.add(fromConfig2, goingBack);
if (!rule4nextTile.trackPieceIsLegal(fromConfig2)) {
return false;
}
/*
* Set the using existing track. We do this because a path that uses
* existing track is cheaper to build.
*/
usingExistingTrack = trackAlreadyPresent1.contains(goingTo);
return true;
}
private TrackRule getAppropriateTrackRule(int x, int y) {
final FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
TrackRule rule;
if (!tile.hasTrack()) {
int terrainTypeID = tile.getTerrainTypeID();
int trackRuleID = buildTrackStrategy.getRule(terrainTypeID);
if (trackRuleID == -1) {
return null; // Can't build on this terrain!
}
rule = (TrackRule) world.get(SKEY.TRACK_RULES, trackRuleID);
} else {
rule = tile.getTrackPiece().getTrackRule();
}
return rule;
}
/**
* Calculates a cost figure incorporating the distance and the cost of any
* new track.
*/
public int getEdgeCost() {
if (beforeFirst) {
throw new IllegalStateException();
}
Step edgeDirection = Step.getInstance(directionInt - 1);
double length = edgeDirection.getLength();
final int DISTANCE_COST = 10000; // Same as the cost of standard
// track.
int cost = (int) Math.round(DISTANCE_COST * length);
if (!usingExistingTrack) {
int[] x = { currentPosition.getX(),
currentPosition.getX() + edgeDirection.deltaX };
int[] y = { currentPosition.getY(),
currentPosition.getY() + edgeDirection.deltaY };
TrackRule ruleA = getAppropriateTrackRule(x[0], y[0]);
TrackRule ruleB = getAppropriateTrackRule(x[1], y[1]);
/*
* If there is a station at either of the points, don't include its
* price in the cost calculation since it has already been paid.
* Otherwise, add the cost of building the track.
*/
long priceA = ruleA.getPrice().getAmount();
long priceB = ruleB.getPrice().getAmount();
cost += length * (priceA + priceB);
// Add fixed cost if tile b does not have the desired track type.
FreerailsTile a = (FreerailsTile) world.getTile(x[0], y[0]);
TrackRule currentRuleA = a.getTrackPiece().getTrackRule();
if (!currentRuleA.equals(ruleA)) {
assert (!currentRuleA.isStation()); // We shouldn't be upgrading
// a station.
cost += ruleA.getFixedCost().getAmount() * Step.TILE_DIAMETER;
}
}
return cost;
}
public int getH() {
int xDistance = (target.x - currentPosition.getX())
* Step.TILE_DIAMETER;
int yDistance = (target.y - currentPosition.getY())
* Step.TILE_DIAMETER;
int sumOfSquares = (xDistance * xDistance + yDistance * yDistance);
return (int) Math.sqrt(sumOfSquares);
}
public int getPosition() {
return currentPosition.toInt();
}
public int getVertexConnectedByEdge() {
if (beforeFirst) {
throw new IllegalStateException();
}
return currentBranch.toInt();
}
public boolean hasNextEdge() {
while (directionInt < 8) {
if (canBuildTrack()) {
return true;
}
directionInt++;
}
return false;
}
public void moveForward() {
if (beforeFirst) {
throw new IllegalStateException();
}
setPosition(this.getVertexConnectedByEdge());
}
public void nextEdge() {
if (!hasNextEdge()) {
throw new NoSuchElementException();
}
// The direction we are moving relative to the current position.
Step direction = Step.getInstance(directionInt);
currentBranch.setCameFrom(direction);
currentBranch.setX(currentPosition.getX() + direction.getDx());
currentBranch.setY(currentPosition.getY() + direction.getDy());
directionInt++;
beforeFirst = false;
}
public void setPosition(int vertex) {
currentPosition.setValuesFromInt(vertex);
directionInt = 0;
}
public void setBuildTrackStrategy(BuildTrackStrategy trackStrategy) {
if (null == trackStrategy)
throw new NullPointerException();
buildTrackStrategy = trackStrategy;
}
}
Methods:
MethodJavadoc
canBuildTrack/**
getAppropriateTrackRule
getEdgeCost/**
getH
getPosition
getVertexConnectedByEdge
hasNextEdge
moveForward
nextEdge
setBuildTrackStrategy
setPosition
jfreerails.controller.BuildTrackStrategy
Javadoc:
/** * A BuildTrackStrategy determines which track types to build (or upgrade to) on * different terrains. * * @author Luke */
Source code:
/**
* A BuildTrackStrategy determines which track types to build (or upgrade to) on
* different terrains.
*
* @author Luke
*/
public class BuildTrackStrategy {
private final int[] rules;
public static BuildTrackStrategy getSingleRuleInstance(int trackTypeID,
ReadOnlyWorld w) {
int noTerrainTypes = w.size(SKEY.TERRAIN_TYPES);
int[] newRules = new int[noTerrainTypes];
for (int i = 0; i < noTerrainTypes; i++) {
newRules[i] = trackTypeID;
}
return new BuildTrackStrategy(newRules);
}
public static BuildTrackStrategy getMultipleRuleInstance(
ArrayList<Integer> ruleIDs, ReadOnlyWorld w) {
int[] rulesArray = generateRules(ruleIDs, w);
return new BuildTrackStrategy(rulesArray);
}
public static BuildTrackStrategy getDefault(ReadOnlyWorld w) {
ArrayList<Integer> allowable = new ArrayList<Integer>();
allowable.add(getCheapest(TrackRule.TrackCategories.track, w));
allowable.add(getCheapest(TrackRule.TrackCategories.bridge, w));
allowable.add(getCheapest(TrackRule.TrackCategories.tunnel, w));
return new BuildTrackStrategy(generateRules(allowable, w));
}
private static Integer getCheapest(TrackRule.TrackCategories category,
ReadOnlyWorld w) {
TrackRule cheapest = null;
Integer cheapestID = null;
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule rule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
if (rule.getCategory().equals(category)) {
if (null == cheapest
|| cheapest.getPrice().getAmount() > rule.getPrice()
.getAmount()) {
cheapest = rule;
cheapestID = new Integer(i);
}
}
}
return cheapestID;
}
private static int[] generateRules(ArrayList<Integer> allowable,
ReadOnlyWorld w) {
int noTerrainTypes = w.size(SKEY.TERRAIN_TYPES);
int[] newRules = new int[noTerrainTypes];
for (int i = 0; i < noTerrainTypes; i++) {
TerrainType terrainType = (TerrainType) w
.get(SKEY.TERRAIN_TYPES, i);
newRules[i] = -1; // the default value.
for (Integer rule : allowable) {
if (null != rule) {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES,
rule.intValue());
if (trackRule.canBuildOnThisTerrainType(terrainType
.getCategory())) {
newRules[i] = rule.intValue();
break;
}
}
}
}
return newRules;
}
/** Creates a new instance of BuildTrackStrategy */
private BuildTrackStrategy(int[] r) {
rules = r;
}
public int getRule(int terrainType) {
return rules[terrainType];
}
}
Methods:
MethodJavadoc
generateRules
getCheapest
getDefault
getMultipleRuleInstance
getRule
getSingleRuleInstance
jfreerails.controller.CalcCargoSupplyRateAtStation
Javadoc:
/** * This class probes the tiles adjacent to a station for what cargo they supply, * demand, and convert and then returns a vector of these rates. * * @author Scott Bennett * @author Luke Created: 9th May 2003 */
Source code:
/**
* This class probes the tiles adjacent to a station for what cargo they supply,
* demand, and convert and then returns a vector of these rates.
*
* @author Scott Bennett
* @author Luke Created: 9th May 2003
*/
public class CalcCargoSupplyRateAtStation {
private static final Logger logger = Logger
.getLogger(CalcCargoSupplyRateAtStation.class.getName());
/**
* The threshold that demand for a cargo must exceed before the station
* demands the cargo.
*/
private static final int PREREQUISITE_FOR_DEMAND = 16;
private final int[] converts;
private final int[] demand;
private final Vector<CargoElementObject> supplies;
private final ReadOnlyWorld w;
private int x;
private int y;
private int stationRadius;
/**
* Call this constructor if the station does not exist yet.
*
* @param trackRuleNo
* the station type.
*/
public CalcCargoSupplyRateAtStation(ReadOnlyWorld world, int X, int Y,
int trackRuleNo) {
this.w = world;
this.x = X;
this.y = Y;
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, trackRuleNo);
stationRadius = trackRule.getStationRadius();
supplies = new Vector<CargoElementObject>();
populateSuppliesVector();
int numCargoTypes = w.size(SKEY.CARGO_TYPES);
demand = new int[numCargoTypes];
converts = ConvertedAtStation.emptyConversionArray(numCargoTypes);
}
/** Call this constructor if the station already exists. */
public CalcCargoSupplyRateAtStation(ReadOnlyWorld world, int X, int Y) {
this(world, X, Y, findTrackRule(X, Y, world));
}
public ConvertedAtStation getConversion() {
return new ConvertedAtStation(this.converts);
}
public Demand4Cargo getDemand() {
boolean[] demandboolean = new boolean[w.size(SKEY.CARGO_TYPES)];
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
if (demand[i] >= PREREQUISITE_FOR_DEMAND) {
demandboolean[i] = true;
}
}
return new Demand4Cargo(demandboolean);
}
private void incrementSupplyAndDemand(int i, int j) {
int tileTypeNumber = ((FreerailsTile) w.getTile(i, j))
.getTerrainTypeID();
TerrainType terrainType = (TerrainType) w.get(SKEY.TERRAIN_TYPES,
tileTypeNumber);
// Calculate supply.
ImList<Production> production = terrainType.getProduction();
// loop through the production array and increment
// the supply rates for the station
for (int m = 0; m < production.size(); m++) {
int type = production.get(m).getCargoType();
int rate = production.get(m).getRate();
// loop through supplies vector and increment the cargo values as
// required
updateSupplyRate(type, rate);
}
// Now calculate demand.
ImList<Consumption> consumption = terrainType.getConsumption();
for (int m = 0; m < consumption.size(); m++) {
int type = consumption.get(m).getCargoType();
int prerequisite = consumption.get(m).getPrerequisite();
// The prerequisite is the number tiles of this type that must
// be within the station radius before the station demands the
// cargo.
demand[type] += PREREQUISITE_FOR_DEMAND / prerequisite;
}
ImList<Conversion> conversion = terrainType.getConversion();
for (int m = 0; m < conversion.size(); m++) {
int type = conversion.get(m).getInput();
// Only one tile that converts the cargo type is needed for the
// station to demand the cargo type.
demand[type] += PREREQUISITE_FOR_DEMAND;
converts[type] = conversion.get(m).getOutput();
}
}
private void populateSuppliesVector() {
// fill supplies vector with 0 values for all cargo types
// get the correct list of cargoes from the world object
CargoElementObject tempCargoElement;
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
// cT = (CargoType) w.get(SKEY.CARGO_TYPES, i);
tempCargoElement = new CargoElementObject(0, i);
supplies.add(tempCargoElement);
}
}
public Vector<CargoElementObject> scanAdjacentTiles() {
int stationDiameter = stationRadius * 2 + 1;
Rectangle stationRadiusRect = new Rectangle(x - stationRadius, y
- stationRadius, stationDiameter, stationDiameter);
Rectangle mapRect = new Rectangle(0, 0, w.getMapWidth(), w
.getMapHeight());
Rectangle tiles2scan = stationRadiusRect.intersection(mapRect);
logger.fine("stationRadiusRect=" + stationRadiusRect);
logger.fine("mapRect=" + mapRect);
logger.fine("tiles2scan=" + tiles2scan);
// Look at the terrain type of each tile and retrieve the cargo
// supplied.
// The station radius determines how many tiles each side we look at.
for (int i = tiles2scan.x; i < (tiles2scan.x + tiles2scan.width); i++) {
for (int j = tiles2scan.y; j < (tiles2scan.y + tiles2scan.height); j++) {
incrementSupplyAndDemand(i, j);
}
}
// return the supplied cargo rates
return supplies;
}
private static int findTrackRule(int xx, int yy, ReadOnlyWorld w) {
FreerailsTile tile = (FreerailsTile) w.getTile(xx, yy);
int ruleNumber = tile.getTrackPiece().getTrackTypeID();
return ruleNumber;
}
private void updateSupplyRate(int type, int rate) {
// loop through supplies vector and increment the cargo values as
// required
for (int n = 0; n < supplies.size(); n++) {
CargoElementObject tempElement = supplies.elementAt(n);
if (tempElement.getType() == type) {
// cargo types are the same, so increment the rate in supply
// with the rate.
tempElement.setRate(tempElement.getRate() + rate);
break; // no need to go through the rest if we've found a match
}
}
}
/**
*
* Process each existing station, updating what is supplied to it.
*
* @param station
* A StationModel object to be processed
*
*/
public StationModel calculations(StationModel station) {
int[] cargoSupplied = new int[w.size(SKEY.CARGO_TYPES)];
Vector<CargoElementObject> supply = scanAdjacentTiles();
// grab the supply rates from the vector
for (int i = 0; i < supply.size(); i++) {
cargoSupplied[i] = supply.get(i).getRate();
}
// set the supply rates for the current station
SupplyAtStation supplyAtStation = new SupplyAtStation(cargoSupplied);
station = new StationModel(station, supplyAtStation);
station = new StationModel(station, getDemand());
station = new StationModel(station, getConversion());
return station;
}
}
Methods:
MethodJavadoc
calculations/**
findTrackRule
getConversion
getDemand
incrementSupplyAndDemand
populateSuppliesVector
scanAdjacentTiles
updateSupplyRate
jfreerails.controller.CalcNearestCity
Javadoc:
/** * * * Class to find the nearest city and return that name, so that a station can be * named appropriately. Date: 12th April 2003 * * @author Scott Bennett */
Source code:
/**
*
*
* Class to find the nearest city and return that name, so that a station can be
* named appropriately. Date: 12th April 2003
*
* @author Scott Bennett
*/
public class CalcNearestCity {
private final int x;
private final int y;
private final ReadOnlyWorld w;
public CalcNearestCity(ReadOnlyWorld world, int x, int y) {
this.w = world;
this.x = x;
this.y = y;
}
public String findNearestCity() {
double cityDistance;
String cityName = null;
double tempDistance;
CityModel tempCity;
if (w.size(SKEY.CITIES) > 0) {
tempCity = (CityModel) w.get(SKEY.CITIES, 0);
cityDistance = getDistance(tempCity.getCityX(), tempCity.getCityY());
cityName = tempCity.getCityName();
for (int i = 1; i < w.size(SKEY.CITIES); i++) {
tempCity = (CityModel) w.get(SKEY.CITIES, i);
tempDistance = getDistance(tempCity.getCityX(), tempCity
.getCityY());
if (tempDistance < cityDistance) {
cityDistance = tempDistance;
cityName = tempCity.getCityName();
}
}
return cityName;
}
throw new NoSuchElementException();
}
private double getDistance(int cityX, int cityY) {
double distance = 0;
double a = (this.x - cityX) * (this.x - cityX);
double b = (this.y - cityY) * (this.y - cityY);
distance = Math.sqrt(a + b);
return distance;
}
}
Methods:
MethodJavadoc
findNearestCity
getDistance
jfreerails.controller.CargoElementObject
Javadoc:
/** * Small data object to store the rate of supply of a cargo. * * @author Scott Bennett Date: 14 May 2003 */
Source code:
/**
* Small data object to store the rate of supply of a cargo.
*
* @author Scott Bennett Date: 14 May 2003
*/
public class CargoElementObject {
private int rate;
private final int type;
public CargoElementObject(int rate, int type) {
this.rate = rate;
this.type = type;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
public int getType() {
return type;
}
}
Methods:
MethodJavadoc
getRate
getType
setRate/**
jfreerails.controller.ClientControlInterface
Javadoc:
/** * Defines the methods that the server can call on a client using a * Message2Client. * * @see Message2Client * @author Luke * */
Source code:
/**
* Defines the methods that the server can call on a client using a
* Message2Client.
*
* @see Message2Client
* @author Luke
*
*/
public interface ClientControlInterface {
public enum ClientProperty {CONNECTED_CLIENTS, MAPS_AVAILABLE, SAVED_GAMES}
/** Called when a new game is started or a game is loaded. */
void setGameModel(FreerailsMutableSerializable world);
/** Sets a property, for example, the list of saved games. */
void setProperty(ClientProperty propertyName, Serializable value);
}
Methods:
MethodJavadoc
setGameModel/** Called when a new game is started or a game is loaded. */
setProperty/** Sets a property, for example, the list of saved games. */
jfreerails.controller.CopyableTextJPanel
Javadoc:
/** * Displays text that can be selected with the mouse and copied to the clipboard. * * @author Luke */
Source code:
/**
* Displays text that can be selected with the mouse and copied to the clipboard.
*
* @author Luke
*/
public class CopyableTextJPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 4076159955353400345L;
/** Creates new form CopyableTextJPanel */
public CopyableTextJPanel() {
initComponents();
}
public void setText(String s){
this.jTextArea1.setText(s);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jPopupMenu1 = new javax.swing.JPopupMenu();
copyItem = new javax.swing.JMenuItem();
selectAllItem = new javax.swing.JMenuItem();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
copyItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
copyItem.setText("Copy");
copyItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
copyItemActionPerformed(evt);
}
});
jPopupMenu1.add(copyItem);
selectAllItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
selectAllItem.setText("Select All");
selectAllItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectAllItemActionPerformed(evt);
}
});
jPopupMenu1.add(selectAllItem);
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(500, 300));
jTextArea1.setEditable(false);
jTextArea1.setText("dsfasd\n\nsad\nf\nasd\nfa\nsdf\nas\ndf\nas\ndf\nads\nf\nasd\nf\nads\nf\ndsa\nf\ndsa\nf\ndasf\na\ndsf\nads\nf\nasd\nf\nasd\nf\n\nasdf");
jTextArea1.setWrapStyleWord(true);
jTextArea1.setOpaque(false);
jTextArea1.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextArea1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTextArea1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}
// </editor-fold>//GEN-END:initComponents
private void selectAllItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectAllItemActionPerformed
jTextArea1.selectAll();
}//GEN-LAST:event_selectAllItemActionPerformed
private void copyItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copyItemActionPerformed
jTextArea1.copy();
}//GEN-LAST:event_copyItemActionPerformed
private void jTextArea1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextArea1MouseClicked
if(SwingUtilities.isRightMouseButton(evt)){
jPopupMenu1.show(jTextArea1, evt.getX(), evt.getY());
}
}//GEN-LAST:event_jTextArea1MouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JMenuItem copyItem;
javax.swing.JPopupMenu jPopupMenu1;
javax.swing.JScrollPane jScrollPane1;
javax.swing.JTextArea jTextArea1;
javax.swing.JMenuItem selectAllItem;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
copyItemActionPerformed
initComponents/** This method is called from within the constructor to
jTextArea1MouseClicked
selectAllItemActionPerformed
setText
jfreerails.controller.DropOffAndPickupCargoMoveGenerator
Javadoc:
/** * This class generates moves that transfer cargo between train and the stations * it stops at - it also handles cargo conversions that occur when cargo is * dropped off. * * @author Scott Bennett * @author Luke Lindsay Date Created: 4 June 2003 */
Source code:
/**
* This class generates moves that transfer cargo between train and the stations
* it stops at - it also handles cargo conversions that occur when cargo is
* dropped off.
*
* @author Scott Bennett
* @author Luke Lindsay Date Created: 4 June 2003
*/
public class DropOffAndPickupCargoMoveGenerator {
private final ReadOnlyWorld w;
private final TrainAccessor train;
private final int trainId;
private int trainBundleId;
private final int stationId;
private int stationBundleId;
private MutableCargoBundle stationAfter;
private MutableCargoBundle stationBefore;
private MutableCargoBundle trainAfter;
private MutableCargoBundle trainBefore;
private ArrayList<Move> moves;
private final FreerailsPrincipal principal;
private boolean waitingForFullLoad;
private boolean autoConsist;
private ImInts consist = new ImInts();
/**
* Stores the type and quantity of cargo in a wagon.
*
* @author Luke
*/
private static class WagonLoad implements Comparable<WagonLoad> {
final int quantity;
final int cargoType;
public int compareTo(WagonLoad test) {
return quantity - test.quantity;
}
WagonLoad(int q, int t) {
quantity = q;
cargoType = t;
}
}
/**
* Constructor.
*
* @param trainNo
* ID of the train
* @param stationNo
* ID of the station
* @param world
* The world object
*/
public DropOffAndPickupCargoMoveGenerator(int trainNo, int stationNo, ReadOnlyWorld world,
FreerailsPrincipal p, boolean waiting, boolean autoConsist) {
principal = p;
trainId = trainNo;
stationId = stationNo;
w = world;
this.autoConsist = autoConsist;
this.waitingForFullLoad = waiting;
train = new TrainAccessor(w, principal, trainNo);
consist = train.getTrain().getConsist();
getBundles();
processTrainBundle(); // ie. unload train / dropoff cargo
if (autoConsist) {
ArrayList<WagonLoad> wagonsAvailable = new ArrayList<WagonLoad>();
assert (train.equals(world.get(principal, KEY.TRAINS, this.trainId)));
Schedule schedule = train.getSchedule();
TrainOrdersModel order = schedule.getOrder(schedule.getOrderToGoto());
int nextStationId = order.stationId;
StationModel stationModel = (StationModel) w
.get(principal, KEY.STATIONS, nextStationId);
Demand4Cargo demand = stationModel.getDemand();
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
// If this cargo is demanded at the next scheduled station.
if (demand.isCargoDemanded(i)) {
int amount = stationAfter.getAmount(i);
while (amount > 0) {
int amount2remove = Math.min(amount, WagonType.UNITS_OF_CARGO_PER_WAGON);
amount -= amount2remove;
// Don't bother with less than half a wagon load.
if (amount2remove * 2 > WagonType.UNITS_OF_CARGO_PER_WAGON) {
wagonsAvailable.add(new WagonLoad(amount2remove, i));
}
}
}
}
Collections.sort(wagonsAvailable);
int numWagons2add = Math.min(wagonsAvailable.size(), 3);
int[] temp = new int[numWagons2add];
for (int i = 0; i < numWagons2add; i++) {
WagonLoad wagonload = wagonsAvailable.get(i);
temp[i] = wagonload.cargoType;
}
consist = new ImInts(temp);
}
processStationBundle(); // ie. load train / pickup cargo
}
public Move generateMove() {
// The methods that calculate the before and after bundles could be
// called from here.
ChangeCargoBundleMove changeAtStation = new ChangeCargoBundleMove(stationBefore
.toImmutableCargoBundle(), stationAfter.toImmutableCargoBundle(), stationBundleId,
principal);
ChangeCargoBundleMove changeOnTrain = new ChangeCargoBundleMove(trainBefore
.toImmutableCargoBundle(), trainAfter.toImmutableCargoBundle(), trainBundleId,
principal);
moves.add(TransferCargoAtStationMove.CHANGE_AT_STATION_INDEX, changeAtStation);
moves.add(TransferCargoAtStationMove.CHANGE_ON_TRAIN_INDEX, changeOnTrain);
if (autoConsist) {
int engine = train.getTrain().getEngineType();
Move m = ChangeTrainMove.generateMove(this.trainId, train.getTrain(), engine, consist, principal);
moves.add(m);
} else if (waitingForFullLoad) {
// Only generate a move if there is some cargo to add..
if (changeOnTrain.beforeEqualsAfter())
return null;
}
TransferCargoAtStationMove move = new TransferCargoAtStationMove(moves, waitingForFullLoad);
assert move.getChangeAtStation() == changeAtStation;
assert move.getChangeOnTrain() == changeOnTrain;
return move;
}
private void getBundles() {
TrainModel trainModel = ((TrainModel) w.get(principal, KEY.TRAINS, trainId));
trainBundleId = trainModel.getCargoBundleID();
trainBefore = getCopyOfBundle(trainBundleId);
trainAfter = getCopyOfBundle(trainBundleId);
StationModel stationModel = ((StationModel) w.get(principal, KEY.STATIONS, stationId));
stationBundleId = stationModel.getCargoBundleID();
stationAfter = getCopyOfBundle(stationBundleId);
stationBefore = getCopyOfBundle(stationBundleId);
}
private MutableCargoBundle getCopyOfBundle(int id) {
FreerailsSerializable fs = w.get(principal, KEY.CARGO_BUNDLES, id);
ImmutableCargoBundle ibundle = (ImmutableCargoBundle) fs;
return new MutableCargoBundle(ibundle);
}
private void processTrainBundle() {
Iterator<CargoBatch> batches = trainAfter.toImmutableCargoBundle().cargoBatchIterator();
StationModel station = (StationModel) w.get(principal, KEY.STATIONS, stationId);
MutableCargoBundle cargoDroppedOff = new MutableCargoBundle();
// Unload the cargo that the station demands
while (batches.hasNext()) {
CargoBatch cb = batches.next();
// if the cargo is demanded and its not from this station
// originally...
Demand4Cargo demand = station.getDemand();
int cargoType = cb.getCargoType();
if ((demand.isCargoDemanded(cargoType)) && (stationId != cb.getStationOfOrigin())) {
int amount = trainAfter.getAmount(cb);
cargoDroppedOff.addCargo(cb, amount);
// Now perform any conversions..
ConvertedAtStation converted = station.getConverted();
if (converted.isCargoConverted(cargoType)) {
int newCargoType = converted.getConversion(cargoType);
CargoBatch newCargoBatch = new CargoBatch(newCargoType, station.x, station.y,
0, stationId);
stationAfter.addCargo(newCargoBatch, amount);
}
trainAfter.setAmount(cb, 0);
}
}
moves = ProcessCargoAtStationMoveGenerator.processCargo(w, cargoDroppedOff, this.stationId,
principal, trainId);
// Unload the cargo that there isn't space for on the train regardless
// of whether the station
// demands it.
ImInts spaceAvailable = train.spaceAvailable();
for (int cargoType = 0; cargoType < spaceAvailable.size(); cargoType++) {
int quantity = spaceAvailable.get(cargoType);
if (quantity < 0) {
int amount2transfer = -quantity;
transferCargo(cargoType, amount2transfer, trainAfter, stationAfter);
}
}
}
/** Transfer cargo from the station to the train subject to the space available on the train.
*/
private void processStationBundle() {
ImInts spaceAvailable = TrainAccessor.spaceAvailable2(w, trainAfter.toImmutableCargoBundle(), consist);
for (int cargoType = 0; cargoType < spaceAvailable.size(); cargoType++) {
int quantity = spaceAvailable.get(cargoType);
int amount2transfer = Math.min(quantity, stationAfter
.getAmount(cargoType));
transferCargo(cargoType, amount2transfer, stationAfter, trainAfter);
}
}
public boolean isCargo2Transfer() {
ImInts spaceAvailable = train.spaceAvailable();
int total = 0;
for (int cargoType = 0; cargoType < w.size(SKEY.CARGO_TYPES); cargoType++) {
int quantity = spaceAvailable.get(cargoType);
int amount2transfer = Math.min(quantity, stationAfter
.getAmount(cargoType));
total += amount2transfer;
}
return total > 0;
}
/**
* Move the specified quantity of the specified cargotype from one bundle to
* another.
*/
private static void transferCargo(int cargoTypeToTransfer, int amountToTransfer,
MutableCargoBundle from, MutableCargoBundle to) {
if (0 == amountToTransfer) {
return;
}
Iterator<CargoBatch> batches = from.toImmutableCargoBundle().cargoBatchIterator();
int amountTransferredSoFar = 0;
while (batches.hasNext() && amountTransferredSoFar < amountToTransfer) {
CargoBatch cb = batches.next();
if (cb.getCargoType() == cargoTypeToTransfer) {
int amount = from.getAmount(cb);
int amountOfThisBatchToTransfer;
if (amount < amountToTransfer - amountTransferredSoFar) {
amountOfThisBatchToTransfer = amount;
from.setAmount(cb, 0);
} else {
amountOfThisBatchToTransfer = amountToTransfer - amountTransferredSoFar;
from.addCargo(cb, -amountOfThisBatchToTransfer);
}
to.addCargo(cb, amountOfThisBatchToTransfer);
amountTransferredSoFar += amountOfThisBatchToTransfer;
}
}
}
}
Methods:
MethodJavadoc
generateMove
getBundles
getCopyOfBundle
isCargo2Transfer
processStationBundle/** Transfer cargo from the station to the train subject to the space available on the train.
processTrainBundle
transferCargo/**
jfreerails.controller.FinancialDataGatherer
Javadoc:
/** * Gathers the financial data for a company. * * @author Luke * @author smackay */
Source code:
/**
* Gathers the financial data for a company.
*
* @author Luke
* @author smackay
*/
public class FinancialDataGatherer extends TransactionAggregator {
private int totalShares = 100000;
private final int playerID;
private int bonds;
private int[] stockInRRs;
private int[] stockInThisRRs;
@Override
protected void incrementRunningTotal(int transactionID) {
Transaction t = super.w.getTransaction(super.principal, transactionID);
if (t instanceof AddItemTransaction) {
AddItemTransaction ait = (AddItemTransaction) t;
if (t instanceof StockTransaction
&& ait.getCategory() == Transaction.Category.ISSUE_STOCK
&& ait.getType() == -1) {
// If it is a change in the total number of shares issued.
StockTransaction ist = (StockTransaction) t;
totalShares += ist.getQuantity();
} else if (t instanceof StockTransaction
&& ait.getCategory() == Transaction.Category.TRANSFER_STOCK
) {
//
stockInRRs[ait.getType()] += ait.getQuantity();
} else if (t instanceof BondTransaction) {
bonds += ait.getQuantity();
}
} else {
super.incrementRunningTotal(transactionID);
}
}
@Override
protected void setTotalsArrayLength(int length) {
// TODO Auto-generated method stub
super.setTotalsArrayLength(length);
}
@Override
protected void storeRunningTotal(int timeIndex) {
// TODO Auto-generated method stub
super.storeRunningTotal(timeIndex);
}
public FinancialDataGatherer(ReadOnlyWorld w, FreerailsPrincipal principal) {
super(w, principal);
stockInRRs = new int [w.getNumberOfPlayers()];
calculateValues();
this.playerID = w.getID(principal);
}
public void changeTreasuryStock(int deltaStock) {
}
public void changeStake(int stakeHolder, int deltaStock) {
}
public boolean canIssueBond() {
return nextBondInterestRate() <= 7;
}
public boolean canBuyStock() {
return totalShares > 0;
}
public int nextBondInterestRate() {
EconomicClimate ec = (EconomicClimate) w.get(ITEM.ECONOMIC_CLIMATE);
return bonds + ec.getBaseInterestRate();
}
public int[] bondInterestRates() {
return null;
}
/** Returns the number of stock in the Treasury */
public int treasuryStock() {
return stockInRRs[playerID];
}
/** Returns The number of open Shares */
public int totalShares() {
return totalShares;
}
public int sharesHeldByPublic(){
int[]stock = getStockInThisRRs();
int returnValue = this.totalShares;
for (int i = 0; i < stock.length; i++) {
returnValue -= stock[i];
}
return returnValue;
}
public boolean thisRRHasStakeIn(int otherReId){
return stockInRRs[otherReId] > 0;
}
public Money netWorth() {
NetWorthCalculator nwc = new NetWorthCalculator(w, principal);
GameTime[] times = {GameTime.BIG_BANG, GameTime.END_OF_THE_WORLD};
nwc.setTimes(times);
return nwc.calculateValue();
}
@Override
protected boolean condition(int transactionID) {
// We'll do the work when incrementRunningTotal gets called.
return true;
}
public int[] getStockInThisRRs() {
if(null == stockInThisRRs){
stockInThisRRs = new int[w.getNumberOfPlayers()];
for(int i = 0; i < w.getNumberOfPlayers(); i++){
Player p = w.getPlayer(i);
FinancialDataGatherer temp = new FinancialDataGatherer(w, p.getPrincipal());
stockInThisRRs[i] = temp.stockInRRs[this.playerID];
}
}
return stockInThisRRs;
}
public int[] getStockInRRs() {
return stockInRRs;
}
public int getBonds() {
return bonds;
}
}
Methods:
MethodJavadoc
bondInterestRates/**
canBuyStock
canIssueBond
changeStake
changeTreasuryStock
condition
getBonds
getStockInRRs
getStockInThisRRs
incrementRunningTotal
netWorth
nextBondInterestRate
setTotalsArrayLength
sharesHeldByPublic
storeRunningTotal
thisRRHasStakeIn
totalShares/** Returns The number of open Shares */
treasuryStock/** Returns the number of stock in the Treasury */
jfreerails.controller.FinancialMoveProducer
Javadoc:
/** * Not yet implemented * * @author Luke * */
Source code:
/**
* Not yet implemented
*
* @author Luke
*
*/
public class FinancialMoveProducer {
public static final Money IPO_SHARE_PRICE = new Money(5);
public static final int SHARE_BUNDLE_SIZE = 10000;
public static final int IPO_SIZE = SHARE_BUNDLE_SIZE * 10;
FinancialMoveProducer(ReadOnlyWorld row) {
}
EconomicClimate worsen() {
return null;
}
EconomicClimate improve() {
return null;
}
}
Methods:
MethodJavadoc
improve
worsen
jfreerails.controller.FlatTrackExplorer
Javadoc:
/** * GraphExplorer that explorers track, the ints it returns are encoded * PositionOnTrack objects. * * @author Luke */
Source code:
/**
* GraphExplorer that explorers track, the ints it returns are encoded
* PositionOnTrack objects.
*
* @author Luke
*/
public class FlatTrackExplorer implements GraphExplorer, Serializable {
private static final long serialVersionUID = 3834311713465185081L;
private PositionOnTrack currentPosition = PositionOnTrack.createComingFrom(
0, 0, Step.NORTH);
final PositionOnTrack currentBranch = PositionOnTrack.createComingFrom(0,
0, Step.NORTH);
private boolean beforeFirst = true;
private final ReadOnlyWorld w;
public ReadOnlyWorld getWorld() {
return w;
}
public void setPosition(int i) {
beforeFirst = true;
currentPosition.setValuesFromInt(i);
}
public int getPosition() {
return this.currentPosition.toInt();
}
public void moveForward() {
if (beforeFirst) {
throw new IllegalStateException();
}
this.setPosition(this.getVertexConnectedByEdge());
}
public void nextEdge() {
if (!hasNextEdge()) {
throw new NoSuchElementException();
}
Step v = this.getFirstVectorToTry();
Point p = new Point(currentPosition.getX(), currentPosition.getY());
FreerailsTile ft = (FreerailsTile)w.getTile(p.x, p.y);
TrackPiece tp = ft.getTrackPiece();
TrackConfiguration conf = tp.getTrackConfiguration();
Step[] vectors = Step.getList();
int i = v.getID();
int loopCounter = 0;
while (!conf.contains(vectors[i].get9bitTemplate())) {
i++;
i = i % 8;
loopCounter++;
if (8 < loopCounter) {
throw new IllegalStateException();
// This should never happen.. ..but it does happen when you
// removed the track from under a train.
}
}
Step branchDirection = Step.getInstance(i);
this.currentBranch.setCameFrom(branchDirection);
int x = this.currentPosition.getX() + branchDirection.deltaX;
int y = this.currentPosition.getY() + branchDirection.deltaY;
this.currentBranch.setX(x);
this.currentBranch.setY(y);
beforeFirst = false;
}
public int getVertexConnectedByEdge() {
return currentBranch.toInt();
}
public int getEdgeCost() {
return (int) Math.round(currentBranch.cameFrom().getLength());
}
public boolean hasNextEdge() {
if (beforeFirst) {
// We can always go back the way we have come, so if we are before
// the first
// branch, there must be a branch: the one we used to get here.
return true;
}
// Since we can always go back the way we have come, if the direction of
// current branch is not equal to the opposite of the current direction,
// there must be another branch.
Step currentBranchDirection = this.currentBranch.cameFrom();
Step oppositeToCurrentDirection = this.currentPosition.cameFrom()
.getOpposite();
if (oppositeToCurrentDirection.getID() == currentBranchDirection
.getID()) {
return false;
}
return true;
}
public FlatTrackExplorer(ReadOnlyWorld world, PositionOnTrack p) {
w = world;
FreerailsTile tile = (FreerailsTile) world.getTile(p.getX(), p.getY());
if (tile.getTrackPiece().getTrackTypeID() == NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
throw new IllegalArgumentException(p.toString());
}
this.currentPosition = PositionOnTrack.createComingFrom(p.getX(), p
.getY(), p.cameFrom());
}
/**
* @return an array of PositionOnTrack objects describing the set of
* possible orientations at this position (heading towards the
* center of the tile)
* @param p
* location of track to consider.
*/
public static PositionOnTrack[] getPossiblePositions(ReadOnlyWorld w,
ImPoint p) {
TrackPiece tp = ((FreerailsTile) w.getTile(p.x, p.y)).getTrackPiece();
TrackConfiguration conf = tp.getTrackConfiguration();
Step[] vectors = Step.getList();
// Count the number of possible positions.
int n = 0;
for (int i = 0; i < vectors.length; i++) {
if (conf.contains(vectors[i].get9bitTemplate())) {
n++;
}
}
PositionOnTrack[] possiblePositions = new PositionOnTrack[n];
n = 0;
for (int i = 0; i < vectors.length; i++) {
if (conf.contains(vectors[i].get9bitTemplate())) {
possiblePositions[n] = PositionOnTrack.createComingFrom(p.x,
p.y, vectors[i].getOpposite());
n++;
}
}
return possiblePositions;
}
Step getFirstVectorToTry() {
if (beforeFirst) {
// Return the vector that is 45 degrees clockwise from the opposite
// of the current position.
Step v = this.currentPosition.cameFrom();
v = v.getOpposite();
int i = v.getID();
i++;
i = i % 8;
v = Step.getInstance(i);
return v;
}
// Return the vector that is 45 degrees clockwise from the direction
// of the current branch.
Step v = this.currentBranch.cameFrom();
int i = v.getID();
i++;
i = i % 8;
v = Step.getInstance(i);
return v;
}
public int getH() {
// TODO Auto-generated method stub
return 0;
}
}
Methods:
MethodJavadoc
getEdgeCost
getFirstVectorToTry
getH
getPosition/**
getPossiblePositions/**
getVertexConnectedByEdge
getWorld
hasNextEdge
moveForward
nextEdge
setPosition/**
jfreerails.controller.FreerailsServerSerializable
Javadoc:
/** * Tags classes that the server may need to save but which won't be sent to * clients. * * @author Luke Lindsay * */
Source code:
/**
* Tags classes that the server may need to save but which won't be sent to
* clients.
*
* @author Luke Lindsay
*
*/
public interface FreerailsServerSerializable extends Serializable {
}
No methods in this class.
jfreerails.controller.GraphExplorer
Javadoc:
/** * This interface lets the caller explorer a graph while hiding the way the * graph is stored. Vertices are packed into single ints to avoid the cost of * object creation and garbage collection. * * 24-Nov-2002 * * @author Luke Lindsay */
Source code:
/**
* This interface lets the caller explorer a graph while hiding the way the
* graph is stored. Vertices are packed into single ints to avoid the cost of
* object creation and garbage collection.
*
* 24-Nov-2002
*
* @author Luke Lindsay
*/
public interface GraphExplorer {
void setPosition(int vertex);
/** Return the current edge. */
int getPosition();
/**
* Sets the current edge to the current vertex's next edge. Throws a
* NoSuchElementException if the vertex does not have another edge.
*/
void nextEdge();
/**
* Returns the vertex that is connected to the current vertex by the current
* edge.
*/
int getVertexConnectedByEdge();
/** Returns the cost of the current edge. */
int getEdgeCost();
boolean hasNextEdge();
/**
* Moves this GraphExplorer from the current vertex to the vertex that is
* connected to the current vertex by the current edge.
*/
void moveForward();
int getH();
}
Methods:
MethodJavadoc
getEdgeCost/** Returns the cost of the current edge. */
getH/**
getPosition/** Return the current edge. */
getVertexConnectedByEdge/**
hasNextEdge
moveForward/**
nextEdge/**
setPosition
jfreerails.controller.IncrementalPathFinder
Javadoc:
/** * Defines part of the contract for a pathfinder whose search can be completed * in several steps. * * @author Luke * */
Source code:
/**
* Defines part of the contract for a pathfinder whose search can be completed
* in several steps.
*
* @author Luke
*
*/
public interface IncrementalPathFinder {
// TODO replace with enum.
public static final int PATH_NOT_FOUND = Integer.MIN_VALUE;
public final int PATH_FOUND = Integer.MIN_VALUE + 1;
public static final int SEARCH_PAUSED = Integer.MIN_VALUE + 2;
public static final int SEARCH_NOT_STARTED = Integer.MIN_VALUE + 3;
public abstract int getStatus();
public abstract void search(long maxDuration) throws PathNotFoundException;
public abstract void abandonSearch();
}
Methods:
MethodJavadoc
abandonSearch
getStatus
search
jfreerails.controller.JFrameMinimumSizeEnforcer
Javadoc:
/** * Since there is no setMinimum size method on JFrame, we use an instance of * this class to do the job. * * @author Luke * */
Source code:
/**
* Since there is no setMinimum size method on JFrame, we use an instance of
* this class to do the job.
*
* @author Luke
*
*/
public class JFrameMinimumSizeEnforcer implements ComponentListener {
private final int minWidth;
private final int minHeight;
public JFrameMinimumSizeEnforcer(int w, int h) {
this.minHeight = h;
this.minWidth = w;
}
public void componentResized(ComponentEvent arg0) {
Component c = arg0.getComponent();
int width = c.getWidth();
int height = c.getHeight();
// we check if either the width
// or the height are below minimum
boolean resize = false;
if (width < minWidth) {
resize = true;
width = minWidth;
}
if (height < minHeight) {
resize = true;
height = minHeight;
}
if (resize) {
c.setSize(width, height);
}
}
public void componentMoved(ComponentEvent arg0) {
}
public void componentShown(ComponentEvent arg0) {
}
public void componentHidden(ComponentEvent arg0) {
}
}
Methods:
MethodJavadoc
componentHidden
componentMoved
componentResized
componentShown
jfreerails.controller.Map
Javadoc:
/** * Represents a graph structure for pathfinding, specifically designed for use with A* algorithms. * This class provides methods to navigate through nodes and edges, allowing traversal and cost evaluation. * * @author Your Name * @see GraphExplorer * @see Node */
Source code:
class Map implements GraphExplorer {
// Look at SimpleAStarPathFinderTest.svg to see it
private final Node[] nodes = new Node[] {
new Node(new int[] { 1 }, new int[] { 11 }), // 0
new Node(new int[] { 0, 5, 2 }, new int[] { 11, 4, 8 }), // 1 //
// try
// {11,4,4}
new Node(new int[] { 5, 3, 4, 1 }, new int[] { 5, 10, 12, 8 }), // 2
// //try{5,10,12,4}
new Node(new int[] { 2 }, new int[] { 10 }), // 3
new Node(new int[] { 5, 2 }, new int[] { 18, 12 }), // 4
new Node(new int[] { 1, 6, 4, 2 }, new int[] { 4, 3, 18, 5 }), // 5
new Node(new int[] { 5, 7 }, new int[] { 3, 4 }), // 6
new Node(new int[] { 6 }, new int[] { 4 }), // 7
};
private int position = 0;
private int branch = -1;
public void setPosition(int i) {
this.position = i;
this.branch = -1;
}
public int getPosition() {
return this.position;
}
public void nextEdge() {
if (hasNextEdge()) {
branch++;
} else {
throw new NoSuchElementException();
}
}
public int getVertexConnectedByEdge() {
return nodes[position].edges[branch];
}
public int getEdgeCost() {
return nodes[position].distances[branch];
}
public boolean hasNextEdge() {
if (nodes[position].edges.length > (branch + 1)) {
return true;
}
return false;
}
public void moveForward() {
this.setPosition(this.getVertexConnectedByEdge());
}
public int getH() {
// TODO Auto-generated method stub
return 0;
}
}
Methods:
MethodJavadoc
getEdgeCost
getH
getPosition
getVertexConnectedByEdge
hasNextEdge
moveForward/**
nextEdge
setPosition/**
jfreerails.controller.Message2Client
Javadoc:
/** * Defines a command sent from the server to the client. * * @author Luke * */
Source code:
/**
* Defines a command sent from the server to the client.
*
* @author Luke
*
*/
public interface Message2Client extends FreerailsSerializable {
/** Executes this command on the specified ClientControlInterface. */
MessageStatus execute(ClientControlInterface client);
/** Returns the id of this command. */
int getID();
}
Methods:
MethodJavadoc
execute/** Executes this command on the specified ClientControlInterface. */
getID/** Returns the id of this command. */
jfreerails.controller.Message2Server
Javadoc:
/** * Defines a command sent from a client to the server. * * @author Luke * */
Source code:
/**
* Defines a command sent from a client to the server.
*
* @author Luke
*
*/
public interface Message2Server extends FreerailsSerializable {
int getID();
MessageStatus execute(ServerControlInterface server);
}
Methods:
MethodJavadoc
execute
getID
jfreerails.controller.MessageStatus
Javadoc:
/** * An instance of this class is returned to the client (the server) when a * Message2Server (Message2Client) is executed by the server (the client). * * @see Message2Client * @see Message2Server * @author Luke * */
Source code:
/**
* An instance of this class is returned to the client (the server) when a
* Message2Server (Message2Client) is executed by the server (the client).
*
* @see Message2Client
* @see Message2Server
* @author Luke
*
*/
public class MessageStatus implements FreerailsSerializable {
private static final long serialVersionUID = 3257285842216103987L;
private final int id;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof MessageStatus))
return false;
final MessageStatus messageStatus = (MessageStatus) o;
if (id != messageStatus.id)
return false;
if (successful != messageStatus.successful)
return false;
if (reason != null ? !reason.equals(messageStatus.reason)
: messageStatus.reason != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + (reason != null ? reason.hashCode() : 0);
result = 29 * result + (successful ? 1 : 0);
return result;
}
private final String reason;
private final boolean successful;
public MessageStatus(int id, boolean successful, String reason) {
this.id = id;
this.reason = reason;
this.successful = successful;
}
public MessageStatus(int id, boolean successful) {
this.id = id;
this.reason = null;
this.successful = successful;
}
/** Returns the id of the command whose status this object stores. */
public int getId() {
return id;
}
/** Returns the reason the command failed, may be null. */
public String getReason() {
return reason;
}
/** True if the command was successfully executed. */
public boolean isSuccessful() {
return successful;
}
}
Methods:
MethodJavadoc
getId/** Returns the id of the command whose status this object stores. */
getReason/** Returns the reason the command failed, may be null. */
isSuccessful/** True if the command was successfully executed. */
jfreerails.controller.ModelRoot
Javadoc:
/** * Defines methods and constants that GUI classes can use to access shared data. * * @author Luke * */
Source code:
/**
* Defines methods and constants that GUI classes can use to access shared data.
*
* @author Luke
*
*/
public interface ModelRoot extends MoveExecutor {
public enum Property {
CURSOR_POSITION, CURSOR_MODE, TRACK_BUILDER_MODE, PREVIOUS_CURSOR_MODE, CURSOR_MESSAGE, QUICK_MESSAGE, PERMANENT_MESSAGE, SHOW_STATION_NAMES, SHOW_CARGO_AT_STATIONS, SHOW_STATION_BORDERS, SERVER, PLAY_SOUNDS, BUILD_TRACK_STRATEGY, IGNORE_KEY_EVENTS, PROPOSED_TRACK, SAVED_GAMES_LIST, THINKING_POINT, TIME, SELECTED_TRAIN
}
public enum Value {
PLACE_STATION_CURSOR_MODE, BUILD_TRACK_CURSOR_MODE
}
void sendCommand(Message2Server c);
void setProperty(Property property, Object newValue);
/**
* Tests whether the specified property has the specified value.
*/
boolean is(Property property, Object value);
Object getProperty(Property property);
}
Methods:
MethodJavadoc
getProperty
is/**
sendCommand
setProperty
jfreerails.controller.MoveExecutor
Javadoc:
/** * Lets the caller try and execute Moves. * * @author Luke * */
Source code:
/**
* Lets the caller try and execute Moves.
*
* @author Luke
*
*/
public interface MoveExecutor {
MoveStatus doMove(Move m);
MoveStatus doPreMove(PreMove pm);
MoveStatus tryDoMove(Move m);
ReadOnlyWorld getWorld();
FreerailsPrincipal getPrincipal();
}
Methods:
MethodJavadoc
doMove
doPreMove
getPrincipal
getWorld
tryDoMove
jfreerails.controller.MoveTrainPreMove
Javadoc:
/** * Generates moves for changes in train position and stops at stations. * * @author Luke * */
Source code:
/**
* Generates moves for changes in train position and stops at stations.
*
* @author Luke
*
*/
public class MoveTrainPreMove implements PreMove {
private static final long serialVersionUID = 3545516188269491250L;
private static final Logger logger = Logger.getLogger(MoveTrainPreMove.class
.getName());
/** Uses static method to make testing easier.*/
public static Step findNextStep(ReadOnlyWorld world,
PositionOnTrack currentPosition, ImPoint target) {
PathOnTrackFinder pathFinder = new PathOnTrackFinder(world);
try {
ImPoint location = new ImPoint(currentPosition.getX(),
currentPosition.getY());
pathFinder.setupSearch(location, target);
pathFinder.search(-1);
return pathFinder.pathAsVectors()[0];
} catch (PathNotFoundException e) {
// The pathfinder couldn't find a path so we
// go in any legal direction.
FlatTrackExplorer explorer = new FlatTrackExplorer(world,
currentPosition);
explorer.nextEdge();
int next = explorer.getVertexConnectedByEdge();
PositionOnTrack nextPosition = new PositionOnTrack(next);
return nextPosition.cameFrom();
}
}
private final FreerailsPrincipal principal;
private final int trainID;
public MoveTrainPreMove(int id, FreerailsPrincipal p) {
trainID = id;
principal = p;
}
double acceleration(int wagons) {
return 0.5d/(wagons + 1);
}
/**
* Returns true iff an updated is due.
*
*/
public boolean isUpdateDue(ReadOnlyWorld w) {
GameTime currentTime = w.currentTime();
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
ActivityIterator ai = w.getActivities(principal, trainID);
ai.gotoLastActivity();
double finishTime = ai.getFinishTime();
double ticks = currentTime.getTicks();
boolean hasFinishedLastActivity = Math.floor(finishTime) <= ticks;
TrainActivity trainActivity = ta.getStatus(finishTime);
if(trainActivity == TrainActivity.WAITING_FOR_FULL_LOAD){
//Check whether there is any cargo that can be added to the train.
ImInts spaceAvailable = ta.spaceAvailable();
int stationId = ta.getStationId(ticks);
if(stationId == -1)
throw new IllegalStateException();
StationModel station = (StationModel)w.get(principal, KEY.STATIONS, stationId);
CargoBundle cb = (CargoBundle)w.get(principal, KEY.CARGO_BUNDLES, station.getCargoBundleID());
for(int i = 0; i < spaceAvailable.size(); i++){
int space = spaceAvailable.get(i);
int atStation = cb.getAmount(i);
if(space * atStation > 0){
logger.fine("There is cargo to transfer!");
return true;
}
}
return !ta.keepWaiting();
}
return hasFinishedLastActivity;
}
private ImPoint currentTrainTarget(ReadOnlyWorld w) {
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
return ta.getTarget();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof MoveTrainPreMove))
return false;
final MoveTrainPreMove moveTrainPreMove = (MoveTrainPreMove) o;
if (trainID != moveTrainPreMove.trainID)
return false;
if (!principal.equals(moveTrainPreMove.principal))
return false;
return true;
}
public Move generateMove(ReadOnlyWorld w) {
// Check that we can generate a move.
if (!isUpdateDue(w))
throw new IllegalStateException();
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
TrainMotion tm = ta.findCurrentMotion(Double.MAX_VALUE);
SpeedTimeAndStatus.TrainActivity activity = tm.getActivity();
switch (activity) {
case STOPPED_AT_STATION:
return moveTrain(w);
case READY:
{
// Are we at a station?
TrainStopsHandler stopsHandler = new TrainStopsHandler(trainID,
principal, new WorldDiffs(w));
ta.getStationId(Integer.MAX_VALUE);
PositionOnTrack pot = tm.getFinalPosition();
int x = pot.getX();
int y = pot.getY();
boolean atStation = stopsHandler.getStationID(x, y) >= 0;
TrainMotion nextMotion;
if (atStation) {
// We have just arrived at a station.
double durationOfStationStop = 10;
stopsHandler.arrivesAtPoint(x, y);
SpeedTimeAndStatus.TrainActivity status = stopsHandler.isWaiting4FullLoad() ? WAITING_FOR_FULL_LOAD : STOPPED_AT_STATION;
PathOnTiles path = tm.getPath();
int lastTrainLength = tm.getTrainLength();
int currentTrainLength = stopsHandler.getTrainLength();
//If we are adding wagons we may need to lengthen the path.
if(lastTrainLength < currentTrainLength){
path = TrainStopsHandler.lengthenPath(w, path, currentTrainLength);
}
nextMotion = new TrainMotion(path, currentTrainLength,
durationOfStationStop, status);
// Create a new Move object.
Move trainMove = new NextActivityMove(nextMotion, trainID,
principal);
Move cargoMove = stopsHandler.getMoves();
return new CompositeMove(trainMove, cargoMove);
}
return moveTrain(w);
}
case WAITING_FOR_FULL_LOAD:
{
TrainStopsHandler stopsHandler = new TrainStopsHandler(trainID,
principal, new WorldDiffs(w));
boolean waiting4fullLoad = stopsHandler.refreshWaitingForFullLoad();
Move cargoMove = stopsHandler.getMoves();
if(!waiting4fullLoad){
Move trainMove = moveTrain(w);
if(null != trainMove){
return new CompositeMove(trainMove, cargoMove);
}else{
return cargoMove;
}
}
stopsHandler.makeTrainWait(30);
return cargoMove;
}
default:
throw new UnsupportedOperationException(activity.toString());
}
}
public SpeedTimeAndStatus.TrainActivity getActivity(ReadOnlyWorld w){
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
TrainMotion tm = ta.findCurrentMotion(Integer.MAX_VALUE);
return tm.getActivity();
}
@Override
public int hashCode() {
int result;
result = trainID;
result = 29 * result + principal.hashCode();
return result;
}
private TrainMotion lastMotion(ReadOnlyWorld w) {
ActivityIterator ai = w.getActivities(principal, trainID);
ai.gotoLastActivity();
TrainMotion lastMotion = (TrainMotion) ai.getActivity();
return lastMotion;
}
private Move moveTrain(ReadOnlyWorld w) {
// Find the next vector.
Step nextVector = nextStep(w);
HashMap<TrackSection, Integer> occupiedTrackSections = occupiedTrackSections(w);
TrainMotion motion = lastMotion(w);
PositionOnTrack pot = motion.getFinalPosition();
ImPoint tile = new ImPoint(pot.getX(), pot.getY());
TrackSection desiredTrackSection = new TrackSection(nextVector, tile);
// Check whether the desired track section is single or double track.
ImPoint tileA = desiredTrackSection.tileA();
ImPoint tileB = desiredTrackSection.tileB();
FreerailsTile fta = (FreerailsTile) w.getTile(tileA.x, tileA.y);
FreerailsTile ftb = (FreerailsTile) w.getTile(tileB.x, tileB.y);
TrackPiece tpa = fta.getTrackPiece();
TrackPiece tpb = ftb.getTrackPiece();
int tracks = 1;
if (tpa.getTrackRule().isDouble() && tpb.getTrackRule().isDouble()) {
tracks = 2;
}
if (occupiedTrackSections.containsKey(desiredTrackSection)) {
int trains = occupiedTrackSections.get(desiredTrackSection);
if (trains >= tracks) {
// We need to wait for the track ahead to clear.
return stopTrain(w);
}
}
// Create a new train motion object.
TrainMotion nextMotion = nextMotion(w, nextVector);
return new NextActivityMove(nextMotion, trainID, principal);
}
private HashMap<TrackSection, Integer> occupiedTrackSections(ReadOnlyWorld w) {
HashMap<TrackSection, Integer> occupiedTrackSections = new HashMap<TrackSection, Integer>();
for (int i = 0; i < w.size(principal, KEY.TRAINS); i++) {
TrainModel train = (TrainModel) w.get(principal,
KEY.TRAINS, i);
if (null == train)
continue;
TrainAccessor ta = new TrainAccessor(w, principal, i);
GameTime gt = w.currentTime();
if(ta.isMoving(gt.getTicks())){
HashSet<TrackSection> sections = ta.occupiedTrackSection(gt.getTicks());
for (TrackSection section : sections) {
if(occupiedTrackSections.containsKey(section)){
int count = occupiedTrackSections.get(section);
count++;
occupiedTrackSections.put(section, count);
}else{
occupiedTrackSections.put(section, 1);
}
}
}
}
return occupiedTrackSections;
}
TrainMotion nextMotion(ReadOnlyWorld w, Step v) {
TrainMotion motion = lastMotion(w);
SpeedAgainstTime speeds = nextSpeeds(w, v);
PathOnTiles currentTiles = motion.getTiles(motion.duration());
PathOnTiles pathOnTiles = currentTiles.addSteps(v);
return new TrainMotion(pathOnTiles, currentTiles.steps(), motion
.getTrainLength(), speeds);
}
SpeedAgainstTime nextSpeeds(ReadOnlyWorld w, Step v) {
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
TrainMotion lastMotion = lastMotion(w);
double u = lastMotion.getSpeedAtEnd();
double s = v.getLength();
int wagons = ta.getTrain().getNumberOfWagons();
double a0 = acceleration(wagons);
double topSpeed = topSpeed(wagons);
SpeedAgainstTime newSpeeds;
if (u < topSpeed) {
double t = (topSpeed - u) / a0;
SpeedAgainstTime a = ConstAcc.uat(u, a0, t);
t = s / topSpeed + 1; // Slightly overestimate the time
SpeedAgainstTime b = ConstAcc.uat(topSpeed, 0, t);
newSpeeds = new CompositeSpeedAgainstTime(a, b);
} else {
double t;
t = s / topSpeed + 1; // Slightly overestimate the time
newSpeeds = ConstAcc.uat(topSpeed, 0, t);
}
return newSpeeds;
}
Step nextStep(ReadOnlyWorld w) {
// Find current position.
TrainMotion currentMotion = lastMotion(w);
PositionOnTrack currentPosition = currentMotion.getFinalPosition();
// Find targets
ImPoint targetPoint = currentTrainTarget(w);
return findNextStep(w, currentPosition, targetPoint);
}
public Move stopTrain(ReadOnlyWorld w) {
TrainMotion motion = lastMotion(w);
SpeedAgainstTime stopped = ConstAcc.STOPPED;
double duration = motion.duration();
int trainLength = motion.getTrainLength();
PathOnTiles tiles = motion.getTiles(duration);
int engineDist = tiles.steps();
TrainMotion nextMotion = new TrainMotion(tiles, engineDist,
trainLength, stopped);
return new NextActivityMove(nextMotion, trainID, principal);
}
double topSpeed(int wagons) {
return 10 / (wagons + 1);
}
}
Methods:
MethodJavadoc
acceleration
currentTrainTarget
findNextStep/** Uses static method to make testing easier.*/
generateMove
getActivity
isUpdateDue/**
lastMotion
moveTrain
nextMotion
nextSpeeds
nextStep
occupiedTrackSections
stopTrain
topSpeed
jfreerails.controller.MyDisplayMode
Javadoc:
/** * Stores a DisplayMode and provides a customised implementation of toString * that can be used in menus. * * @author Luke Lindsay */
Source code:
/**
* Stores a DisplayMode and provides a customised implementation of toString
* that can be used in menus.
*
* @author Luke Lindsay
*/
public class MyDisplayMode {
public final DisplayMode displayMode;
public MyDisplayMode(DisplayMode displayMode) {
this.displayMode = displayMode;
}
@Override
public String toString() {
return displayMode.getWidth() + "x" + displayMode.getHeight() + " "
+ displayMode.getBitDepth() + " bit "
+ displayMode.getRefreshRate() + "Hz";
}
@Override
public int hashCode() {
return displayMode.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof MyDisplayMode) {
MyDisplayMode test = (MyDisplayMode) o;
return test.displayMode.equals(this.displayMode);
}
return false;
}
}
No methods in this class.
jfreerails.controller.NetWorthCalculator
Javadoc:
/** * A TransactionAggregator that calculates the networth of a player by * totalling the value of their assets. * * @author Luke * */
Source code:
/**
* A TransactionAggregator that calculates the networth of a player by
* totalling the value of their assets.
*
* @author Luke
*
*/
public class NetWorthCalculator extends TransactionAggregator {
public NetWorthCalculator(ReadOnlyWorld w, FreerailsPrincipal principal) {
super(w, principal);
}
@Override
protected boolean condition(int transactionID) {
Transaction t = super.w.getTransaction(super.principal,
transactionID);
if (t instanceof AddItemTransaction) {
if(t.getCategory().equals(Transaction.Category.ISSUE_STOCK)){
return true;
}
// Since buying something is just converting one asset type to
// another.
return false;
}
return true;
}
}
Methods:
MethodJavadoc
condition
jfreerails.controller.Node
Javadoc:
/** * Represents a node in a graph structure, containing arrays of edges and distances. * This class ensures that the edges and distances arrays are of equal length upon construction. * * @author YourName * @since 1.0 * * @see Graph */
Source code:
class Node {
int[] edges;
int[] distances;
Node(int[] e, int[] d) {
if (e.length != d.length) {
throw new IllegalArgumentException("e.length=" + e.length
+ ", e.length=" + e.length);
}
edges = e;
distances = d;
}
}
No methods in this class.
jfreerails.controller.OpenList
Javadoc:
/** * An OpenList for SimpleAStarPathFinder. * * @author Luke * */
Source code:
/**
* An OpenList for SimpleAStarPathFinder.
*
* @author Luke
*
*/
class OpenList implements Serializable {
private static final long serialVersionUID = 3257282539419611442L;
static class OpenListEntry implements Comparable<OpenListEntry>,
Serializable {
private static final long serialVersionUID = -4873508719707382681L;
final int f;
final int node;
OpenListEntry(int _f, int _node) {
this.f = _f;
this.node = _node;
}
public int compareTo(OpenListEntry o) {
// XXX Work around for JDK Bug ID: 6207984
if (f == o.f) {
return node - o.node;
}
return f - o.f;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof OpenListEntry))
return false;
final OpenListEntry openListEntry = (OpenListEntry) o;
if (f != openListEntry.f)
return false;
if (node != openListEntry.node)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = f;
result = 29 * result + node;
return result;
}
@Override
public String toString() {
return "OpenListEntry{node=" + node + ", f=" + f + "}";
}
}
private HashMap<Integer, OpenListEntry> map = new HashMap<Integer, OpenListEntry>();
private PriorityQueue<OpenListEntry> queue = new PriorityQueue<OpenListEntry>();
public OpenList() {
}
void clear() {
queue.clear();
map.clear();
}
int getF(int node) {
int f = map.get(node).f;
return f;
}
void add(int node, int f) {
if (map.containsKey(node)) {
OpenListEntry old = map.get(node);
queue.remove(old);
map.remove(node);
}
OpenList.OpenListEntry entry = new OpenListEntry(f, node);
queue.offer(entry);
map.put(node, entry);
}
boolean contains(int node) {
boolean containsKey = map.containsKey(node);
return containsKey;
}
int smallestF() {
OpenListEntry entry = queue.peek();
return entry.f;
}
int popNodeWithSmallestF() {
OpenListEntry entry = queue.remove();
int node = entry.node;
OpenListEntry removed = map.remove(node);
if (null == removed) {
System.out.println("Shizer, size =" + queue.size());
}
return node;
}
int size() {
return queue.size();
}
}
Methods:
MethodJavadoc
add
clear
contains
getF
popNodeWithSmallestF
size
smallestF
jfreerails.controller.PathNotFoundException
Javadoc:
/** * Thrown when a path cannot be found. * * @author Luke * */
Source code:
/**
* Thrown when a path cannot be found.
*
* @author Luke
*
*/
public class PathNotFoundException extends Exception {
private static final long serialVersionUID = 4121409601112717368L;
public PathNotFoundException(String arg0) {
super(arg0);
}
}
No methods in this class.
jfreerails.controller.PathOnTrackFinder
Javadoc:
/** * Finds a path along existing track. Used for upgrading or removing track * between two points on the track. * * @author Luke * */
Source code:
/**
* Finds a path along existing track. Used for upgrading or removing track
* between two points on the track.
*
* @author Luke
*
*/
public class PathOnTrackFinder implements IncrementalPathFinder {
private static final Logger logger = Logger
.getLogger(IncrementalPathFinder.class.getName());
private SimpleAStarPathFinder pathFinder = new SimpleAStarPathFinder();
private ImPoint startPoint;
private final ReadOnlyWorld world;
public PathOnTrackFinder(ReadOnlyWorld world) {
this.world = world;
}
public void abandonSearch() {
pathFinder.abandonSearch();
}
public int getStatus() {
return pathFinder.getStatus();
}
public Step[] pathAsVectors() {
int[] pathAsInts = pathFinder.retrievePath().toArray();
Step[] vectors = new Step[pathAsInts.length];
int x = startPoint.x;
int y = startPoint.y;
for (int i = 0; i < pathAsInts.length; i++) {
PositionOnTrack p2 = new PositionOnTrack(pathAsInts[i]);
vectors[i] = Step.getInstance(p2.getX() - x, p2.getY() - y);
x = p2.getX();
y = p2.getY();
}
return vectors;
}
public void search(long maxDuration) throws PathNotFoundException {
pathFinder.search(maxDuration);
}
public void setupSearch(ImPoint from, ImPoint target) throws PathNotFoundException {
startPoint = from;
logger
.fine("Find track path from " + from + " to "
+ target);
/* Check there is track at both the points. */
FreerailsTile tileA = (FreerailsTile) world.getTile(from.x,
from.y);
FreerailsTile tileB = (FreerailsTile) world.getTile(target.x,
target.y);
if (!tileA.hasTrack()) {
throw new PathNotFoundException("No track at " + from.x
+ ", " + from.y + ".");
}
if (!tileB.hasTrack()) {
throw new PathNotFoundException("No track at " + target.x
+ ", " + target.y + ".");
}
PositionOnTrack[] startPoints = FlatTrackExplorer.getPossiblePositions(
world, from);
PositionOnTrack[] targetPoints = FlatTrackExplorer
.getPossiblePositions(world, target);
FlatTrackExplorer explorer = new FlatTrackExplorer(world,
startPoints[0]);
pathFinder.setupSearch(PositionOnTrack.toInts(startPoints),
PositionOnTrack.toInts(targetPoints), explorer);
}
}
Methods:
MethodJavadoc
abandonSearch
getStatus
pathAsVectors
search
setupSearch
jfreerails.controller.PreMove
Javadoc:
/** * Defines a method that generates a move based on the state of the world * object. The state of a move is often a function of the state of the world * object and some other input. * * @author Luke * */
Source code:
/**
* Defines a method that generates a move based on the state of the world
* object. The state of a move is often a function of the state of the world
* object and some other input.
*
* @author Luke
*
*/
public interface PreMove extends FreerailsSerializable {
Move generateMove(ReadOnlyWorld w);
}
Methods:
MethodJavadoc
generateMove
jfreerails.controller.PreMoveStatus
Javadoc:
/** * Records the success or failure of an attempt to execute a move. * * @author lindsal */
Source code:
/**
* Records the success or failure of an attempt to execute a move.
*
* @author lindsal
*/
final public class PreMoveStatus implements FreerailsSerializable {
private static final long serialVersionUID = 3978145456646009140L;
public static final PreMoveStatus PRE_MOVE_OK = new PreMoveStatus(
MoveStatus.MOVE_OK);
public final MoveStatus ms;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof PreMoveStatus))
return false;
final PreMoveStatus preMoveStatus = (PreMoveStatus) o;
if (!ms.equals(preMoveStatus.ms))
return false;
return true;
}
@Override
public int hashCode() {
return ms.hashCode();
}
/**
* Avoid creating a duplicate when deserializing.
*/
private Object readResolve() {
if (ms.ok) {
return PRE_MOVE_OK;
}
return this;
}
private PreMoveStatus(MoveStatus ms) {
this.ms = ms;
}
public static PreMoveStatus failed(String reason) {
return new PreMoveStatus(MoveStatus.moveFailed(reason));
}
public static PreMoveStatus fromMoveStatus(MoveStatus ms) {
if (ms.ok) {
return PRE_MOVE_OK;
}
return new PreMoveStatus(ms);
}
}
Methods:
MethodJavadoc
failed
fromMoveStatus
readResolve/**
jfreerails.controller.ProcessCargoAtStationMoveGenerator
Javadoc:
/** * This class generates Moves that pay the player for delivering the cargo. * * @author Luke Lindsay * */
Source code:
/**
* This class generates Moves that pay the player for delivering the cargo.
*
* @author Luke Lindsay
*
*/
public class ProcessCargoAtStationMoveGenerator {
/**
* Determines how much the player gets for delivering cargo. Changed from
* 100 to 75 to fix bug 910132 (Too easy to make money!)
*/
private final static int MAGIC_NUMBER = 75;
public static ArrayList<Move> processCargo(ReadOnlyWorld w,
CargoBundle bundle, int stationID, FreerailsPrincipal p,
int trainId) {
StationModel thisStation = (StationModel) w.get(p,
KEY.STATIONS, stationID);
Iterator<CargoBatch> batches = bundle.cargoBatchIterator();
ArrayList<Move> moves = new ArrayList<Move>();
while (batches.hasNext()) {
CargoBatch batch = batches.next();
double distanceSquared = (batch.getSourceX() - thisStation.x)
* (batch.getSourceX() - thisStation.x)
+ (batch.getSourceY() - thisStation.y)
* (batch.getSourceY() - thisStation.y);
double dist = Math.sqrt(distanceSquared);
int quantity = bundle.getAmount(batch);
double amount = quantity * Math.log(dist) * MAGIC_NUMBER;
Money money = new Money((long) amount);
DeliverCargoReceipt receipt = new DeliverCargoReceipt(money,
quantity, stationID, batch, trainId);
moves.add(new AddTransactionMove(p, receipt));
}
return moves;
}
}
Methods:
MethodJavadoc
processCargo
jfreerails.controller.RandomPathFinder
Javadoc:
/** * Returns a random path along the track. * * @author Luke Lindsay 13-Oct-2002 * */
Source code:
/**
* Returns a random path along the track.
*
* @author Luke Lindsay 13-Oct-2002
*
*/
public class RandomPathFinder implements FreerailsPathIterator {
private static final long serialVersionUID = 3832906571880608313L;
private final FlatTrackExplorer trackExplorer;
private final PositionOnTrack p1 = new PositionOnTrack();
private final PositionOnTrack p2 = new PositionOnTrack();
private static final int tileSize = 30;
public RandomPathFinder(FlatTrackExplorer tx) {
trackExplorer = tx;
}
public boolean hasNext() {
return trackExplorer.hasNextEdge();
}
public void nextSegment(IntLine line) {
p1.setValuesFromInt(trackExplorer.getPosition());
line.x1 = p1.getX() * tileSize + tileSize / 2;
line.y1 = p1.getY() * tileSize + tileSize / 2;
trackExplorer.nextEdge();
trackExplorer.moveForward();
p2.setValuesFromInt(trackExplorer.getPosition());
line.x2 = p2.getX() * tileSize + tileSize / 2;
line.y2 = p2.getY() * tileSize + tileSize / 2;
}
}
Methods:
MethodJavadoc
hasNext
nextSegment
jfreerails.controller.ReportBugTextGenerator
Javadoc:
/** * Generates text for bug reports, including instructions and exception details. * This class provides methods to generate bug report text for both general and exception scenarios. * It also handles unexpected exceptions by displaying an error form and exiting the application. * * @see UnexpectedExceptionForm * @see ScreenHandler */
Source code:
public class ReportBugTextGenerator {
private static final String TRACKER_URL = "http://sourceforge.net/tracker/?group_id=9495&atid=109495";
public static void main(String[] args) {
Exception e = genException();
System.out.println(genText());
System.out.println(genText(e));
}
private static Exception genException() {
Exception e = new Exception();
return e;
}
public static String genText() {
StringBuffer sb = new StringBuffer();
sb.append("How to report a bug\n");
sb.append("\n");
sb.append("Use the sourceforge.net bug tracker at the following url:\n");
sb.append(TRACKER_URL);
sb.append("\n");
sb.append("\n");
sb.append("Please include:\n");
sb.append(" 1. Steps to reproduce the bug (attach a save game if appropriate).\n");
sb.append(" 2. What you expected to see.\n");
sb.append(" 3. What you saw instead (attach a screenshot if appropriate).\n");
sb.append(" 4. The details below (copy and past them into the bug report).\n");
appendBuildProps(sb);
sb.append("\n");
sb.append("\n");
return sb.toString();
}
public static String genText(Exception e) {
StackTraceElement[] s = e.getStackTrace();
StringBuffer sb = new StringBuffer();
sb.append("Unexpected Exception\n");
sb.append("\n");
sb.append("Consider submitting a bug report using the sourceforge.net" +
" bug tracker at the following url:\n");
sb.append(TRACKER_URL);
sb.append("\n");
sb.append("\n");
sb.append("Please:\n");
sb.append(" 1. Use the following as the title of the bug report:\n\t");
sb.append(" Unexpected Exception: ");
sb.append(s[0].getFileName());
sb.append(" line ");
sb.append(s[0].getLineNumber());
sb.append("\n");
sb.append(" 2. Include steps to reproduce the bug (attach a save game if appropriate).\n");
sb.append(" 3. Copy and paste the details below into the bug report:\n");
appendBuildProps(sb);
sb.append("\n");
sb.append("\n\t");
sb.append(e.toString());
for (StackTraceElement ste : s) {
sb.append("\n\t\t at ");
sb.append(ste);
}
return sb.toString();
}
private static void appendBuildProps(StringBuffer sb) {
String version = null;
String builtBy = null;;
try {
Properties props = new Properties();
InputStream in = ReportBugTextGenerator.class
.getResourceAsStream("/build.properties");
props.load(in);
in.close();
version = props.getProperty("freerails.build");
builtBy = props.getProperty("freerails.built.by");
} catch (Exception e) {
// ignore, there's nothing useful we can do.
}
version = null == version ? "not set" : version;
builtBy = null == builtBy ? "not set" : builtBy;
sb.append("\t");
sb.append(System.getProperty("os.name"));
sb.append(" ");
sb.append(System.getProperty("os.version"));
sb.append("\n\t");
sb.append(System.getProperty("java.vm.name"));
sb.append(" ");
sb.append(System.getProperty("java.version"));
sb.append("\n\t");
sb.append("Freerails build ");
sb.append(version);
sb.append(" compiled by ");
sb.append(builtBy);
}
@SuppressWarnings("deprecation")
public static void unexpectedException(Exception e) {
ScreenHandler.exitFullScreenMode();
String str = genText(e);
System.err.print(str);
UnexpectedExceptionForm unexpectedExceptionForm = new UnexpectedExceptionForm();
unexpectedExceptionForm.setText(str);
unexpectedExceptionForm.setVisible(true);
if(!EventQueue.isDispatchThread()){
Thread.currentThread().stop();
}
}
}
Methods:
MethodJavadoc
appendBuildProps
genException
genText
genText
main
unexpectedException
jfreerails.controller.ScreenHandler
Javadoc:
/** * Handles going into fullscreen mode and setting buffer strategy etc. * * @author Luke */
Source code:
/**
* Handles going into fullscreen mode and setting buffer strategy etc.
*
* @author Luke
*/
final public class ScreenHandler {
private static final Logger logger = Logger.getLogger(ScreenHandler.class
.getName());
public static final int FULL_SCREEN = 0;
public static final int WINDOWED_MODE = 1;
public static final int FIXED_SIZE_WINDOWED_MODE = 2;
public final JFrame frame;
private BufferStrategy bufferStrategy;
private DisplayMode displayMode;
private final int mode;
private boolean isInUse = false;
/** Whether the window is minimised. */
private boolean isMinimised = false;
static GraphicsDevice device = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice();
public ScreenHandler(JFrame f, int mode, DisplayMode displayMode) {
this.displayMode = displayMode;
frame = f;
this.mode = mode;
}
public ScreenHandler(JFrame f, int mode) {
frame = f;
this.mode = mode;
}
private static void goFullScreen(JFrame frame, DisplayMode displayMode) {
setRepaintOffAndDisableDoubleBuffering(frame);
/*
* We need to make the frame not displayable before calling
* setUndecorated(true) otherwise a
* java.awt.IllegalComponentStateException will get thrown.
*/
if (frame.isDisplayable()) {
frame.dispose();
}
frame.setUndecorated(true);
device.setFullScreenWindow(frame);
if (device.isDisplayChangeSupported()) {
if (null == displayMode) {
displayMode = getBestDisplayMode();
}
logger.info("Setting display mode to: "
+ (new MyDisplayMode(displayMode).toString()));
device.setDisplayMode(displayMode);
}
frame.validate();
}
public synchronized void apply() {
switch (mode) {
case FULL_SCREEN: {
goFullScreen(frame, displayMode);
break;
}
case WINDOWED_MODE: {
// Some of the dialogue boxes do not get layed out properly if they
// are smaller than their
// minimum size. JFrameMinimumSizeEnforcer increases the size of the
// Jframe when its size falls
// below the specified size.
frame.addComponentListener(new JFrameMinimumSizeEnforcer(640, 480));
frame.setSize(640, 480);
frame.setVisible(true);
break;
}
case FIXED_SIZE_WINDOWED_MODE: {
/*
* We need to make the frame not displayable before calling
* setUndecorated(true) otherwise a
* java.awt.IllegalComponentStateException will get thrown.
*/
if (frame.isDisplayable()) {
frame.dispose();
}
frame.setUndecorated(true);
frame.setResizable(false);
frame.setSize(640, 480);
frame.setVisible(true);
break;
}
default:
throw new IllegalArgumentException(String.valueOf(mode));
}
createBufferStrategy();
frame.addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(java.awt.event.ComponentEvent evt) {
createBufferStrategy();
}
});
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowIconified(WindowEvent e) {
isMinimised = true;
}
@Override
public void windowDeiconified(WindowEvent e) {
isMinimised = false;
}
});
isInUse = true;
}
private synchronized void createBufferStrategy() {
// Use 2 backbuffers to avoid using too much VRAM.
frame.createBufferStrategy(2);
bufferStrategy = frame.getBufferStrategy();
setRepaintOffAndDisableDoubleBuffering(frame);
}
public synchronized Graphics getDrawGraphics() {
return bufferStrategy.getDrawGraphics();
}
public synchronized void swapScreens() {
if (!bufferStrategy.contentsLost()) {
bufferStrategy.show();
}
}
private static void setRepaintOffAndDisableDoubleBuffering(Component c) {
c.setIgnoreRepaint(true);
// Since we are using a buffer strategy we don't want Swing
// to double buffer any JComponents.
if (c instanceof JComponent) {
JComponent jComponent = (JComponent) c;
jComponent.setDoubleBuffered(false);
}
if (c instanceof java.awt.Container) {
Component[] children = ((Container) c).getComponents();
for (int i = 0; i < children.length; i++) {
setRepaintOffAndDisableDoubleBuffering(children[i]);
}
}
}
private static DisplayMode getBestDisplayMode() {
for (int x = 0; x < BEST_DISPLAY_MODES.length; x++) {
DisplayMode[] modes = device.getDisplayModes();
for (int i = 0; i < modes.length; i++) {
if (modes[i].getWidth() == BEST_DISPLAY_MODES[x].getWidth()
&& modes[i].getHeight() == BEST_DISPLAY_MODES[x]
.getHeight()
&& modes[i].getBitDepth() == BEST_DISPLAY_MODES[x]
.getBitDepth()) {
logger.fine("Best display mode is "
+ (new MyDisplayMode(BEST_DISPLAY_MODES[x]))
.toString());
return BEST_DISPLAY_MODES[x];
}
}
}
return null;
}
private static final DisplayMode[] BEST_DISPLAY_MODES = new DisplayMode[] {
new DisplayMode(640, 400, 8, 60),
new DisplayMode(800, 600, 16, 60),
new DisplayMode(1024, 768, 8, 60),
new DisplayMode(1024, 768, 16, 60), };
public synchronized boolean isMinimised() {
return isMinimised;
}
public synchronized boolean isInUse() {
return isInUse;
}
public synchronized static void exitFullScreenMode(){
device.setFullScreenWindow(null);
}
public boolean contentsRestored() {
return bufferStrategy.contentsRestored();
}
}
Methods:
MethodJavadoc
apply
contentsRestored
createBufferStrategy
exitFullScreenMode
getBestDisplayMode
getDrawGraphics
goFullScreen
isInUse
isMinimised
setRepaintOffAndDisableDoubleBuffering
swapScreens
jfreerails.controller.ServerControlInterface
Javadoc:
/** * Defines the methods that a client can call on the server using a * Message2Server. * * @see Message2Server * @author Luke * */
Source code:
/**
* Defines the methods that a client can call on the server using a
* Message2Server.
*
* @see Message2Server
* @author Luke
*
*/
public interface ServerControlInterface {
public static final String FREERAILS_SAV = "freerails.sav";
public static final String VERSION = "CVS";
void loadgame(String saveGameName) throws IOException;
void savegame(String saveGameName);
void stopGame();
void refreshSavedGames();
void newGame(String mapName);
}
Methods:
MethodJavadoc
loadgame
newGame
refreshSavedGames
savegame
stopGame
jfreerails.controller.SharePriceCalculator
Javadoc:
/** * @author Luke * */
Source code:
/**
* @author Luke
*
*/
public class SharePriceCalculator {
public int totalShares;
public int treasuryStock;
public int otherRRStakes;
public long profitsLastYear;
public long networth;
public long stockholderEquity;
public long calculatePrice() {
assert totalShares > 0;
assert totalShares >= treasuryStock + otherRRStakes;
assert stockholderEquity > 0;
long price;
long currentValue = networth + stockholderEquity;
long expectedIncrease = profitsLastYear * 5;
int publicOwnedShares = totalShares - treasuryStock - otherRRStakes;
price = 2 * (currentValue + expectedIncrease)
/ (2 * publicOwnedShares + otherRRStakes);
return price;
}
}
Methods:
MethodJavadoc
calculatePrice
jfreerails.controller.SimpleAStarPathFinder
Javadoc:
/** * A simple A* pathfinder implementation. It uses int's to avoid the cost of * object creation and garbage collection. 26-Nov-2002 * * @author Luke Lindsay * */
Source code:
/**
* A simple A* pathfinder implementation. It uses int's to avoid the cost of
* object creation and garbage collection. 26-Nov-2002
*
* @author Luke Lindsay
*
*/
public class SimpleAStarPathFinder implements Serializable,
IncrementalPathFinder {
private static final long serialVersionUID = 3257565105200576310L;
private static final Logger logger = Logger
.getLogger(SimpleAStarPathFinder.class.getName());
private OpenList openList = new OpenList();
private final HashSet<Integer> startingPositions = new HashSet<Integer>();
private final HashMap<Integer, Integer> closedList = new HashMap<Integer, Integer>();
private final HashMap<Integer, Integer> shortestPath = new HashMap<Integer, Integer>();
private int status = SEARCH_NOT_STARTED;
/** Note, IntArray is not Serializable. */
private transient IntArray path = null;
private int bestPath;
private int bestPathF;
private GraphExplorer explorer;
private long searchStartTime = 0;
public int getStatus() {
return status;
}
public IntArray retrievePath() {
return path;
}
public int findstep(int currentPosition, int[] targets,
GraphExplorer tempExplorer) {
try {
return findpath(new int[] { currentPosition }, targets,
tempExplorer).get(0);
} catch (PathNotFoundException e) {
return PATH_NOT_FOUND;
}
}
public IntArray findpath(int[] currentPosition, int[] targets,
GraphExplorer e) throws PathNotFoundException {
logger.fine(currentPosition.length + " starting points; "
+ targets.length + " targets.");
setupSearch(currentPosition, targets, e);
search(-1);
return path;
}
public void search(long maxDuration) throws PathNotFoundException {
long iterationStartTime = 0;
boolean check4timeout = false;
if (maxDuration > 0) {
check4timeout = true;
iterationStartTime = System.currentTimeMillis();
if (searchStartTime == 0) {
searchStartTime = iterationStartTime;
}
}
int loopCounter = 0;
// while the open list is not empty
while (openList.size() > 0) {
// find the node with the least f on the open list, call it "q"
// pop q off the open list
int f = openList.smallestF();
int q = openList.popNodeWithSmallestF();
// generate q's successors.
explorer.setPosition(q);
// for each successor
while (explorer.hasNextEdge()) {
explorer.nextEdge();
int successor = explorer.getVertexConnectedByEdge();
int successorF = f + explorer.getEdgeCost();
// for now, let successor.h=0
// successor.g = q.g + distance between successor and q
// successor.h = distance from goal to successor
// successor.f = successor.g + successor.h
if (startingPositions.contains(successor)) {
// if successor is the goal, we have found a path, but not
// necessarily the shortest.
if (bestPathF > successorF) {
bestPath = q;
bestPathF = successorF;
}
}
if (openList.contains(successor)
&& openList.getF(successor) < successorF) {
// if a node with the same position as successor is in the
// OPEN list \
// which has a lower f than successor, skip this successor
continue;
} else if (closedList.containsKey(successor)
&& closedList.get(successor) < successorF) {
// if a node with the same position as successor is in the
// CLOSED list \
// which has a lower f than successor, skip this successor
continue;
} else {
// otherwise, add the node to the open list
openList.add(successor, successorF);
shortestPath.put(successor, q);
}
}
if (PATH_NOT_FOUND != bestPath) {
int SmallestFOnOpenList = openList.smallestF();
if (bestPathF <= SmallestFOnOpenList) {
// if the F value for the best path we have found so far is
// less than that of the node with the smallest F value on
// the open list, then the best path so far is the shortest
// path.
logger.fine("Path successfully found after " + loopCounter
+ " iterations.");
path.add(bestPath);
int step = bestPath;
while (shortestPath.containsKey(step)) {
step = shortestPath.get(step);
path.add(step);
}
logger.fine("Path found!");
status = PATH_FOUND;
return;
}
}
// push q on the closed list
// PositionOnTrack p = new PositionOnTrack(q);
closedList.put(q, f);
loopCounter++;
// Check whether we have been searching too long.
if (check4timeout && loopCounter % 50 == 0) {
long currentTime = System.currentTimeMillis();
long deltatime = currentTime - iterationStartTime;
if (deltatime > maxDuration) {
status = SEARCH_PAUSED;
long totalSearchTime = currentTime - searchStartTime;
throw new PathNotFoundException("No path found yet. "
+ totalSearchTime + "ms.");
}
}
}
status = PATH_NOT_FOUND;
logger.fine("No path found and open list empty after " + loopCounter
+ " iterations.");
throw new PathNotFoundException("Path not found.");
}
public void setupSearch(int[] currentPosition, int[] targets,
GraphExplorer e) throws PathNotFoundException {
abandonSearch();
explorer = e;
// put the starting nodes on the open list (you can leave its f at zero)
for (int i = 0; i < targets.length; i++) {
openList.add(targets[i], 0);
for (int j = 0; j < currentPosition.length; j++) {
if (targets[i] == currentPosition[j]) {
status = PATH_NOT_FOUND;
throw new PathNotFoundException("Already at target!");
}
}
}
for (int j = 0; j < currentPosition.length; j++) {
startingPositions.add(currentPosition[j]);
}
}
public void abandonSearch() {
path = new IntArray();
searchStartTime = 0;
bestPath = PATH_NOT_FOUND;
bestPathF = Integer.MAX_VALUE;
// initialize the open list
openList.clear();
// initialize the closed list
closedList.clear();
shortestPath.clear();
startingPositions.clear();
status = SEARCH_NOT_STARTED;
}
}
Methods:
MethodJavadoc
abandonSearch
findpath
findstep
getStatus
retrievePath
search
setupSearch
jfreerails.controller.SimpleMoveExecutor
Javadoc:
/** * A MoveExecutor that executes moves on the world object passed to its * constructor. * * @author Luke * */
Source code:
/**
* A MoveExecutor that executes moves on the world object passed to its
* constructor.
*
* @author Luke
*
*/
public class SimpleMoveExecutor implements MoveExecutor {
private final World w;
private final FreerailsPrincipal p;
public SimpleMoveExecutor(World world, int playerID) {
w = world;
Player player = w.getPlayer(playerID);
p = player.getPrincipal();
}
public MoveStatus doMove(Move m) {
return m.doMove(w, p);
}
public MoveStatus doPreMove(PreMove pm) {
Move m = pm.generateMove(w);
return m.doMove(w, p);
}
public MoveStatus tryDoMove(Move m) {
return m.tryDoMove(w, p);
}
public ReadOnlyWorld getWorld() {
return w;
}
public FreerailsPrincipal getPrincipal() {
return p;
}
}
Methods:
MethodJavadoc
doMove
doPreMove
getPrincipal
getWorld
tryDoMove
jfreerails.controller.StationBuilder
Javadoc:
/** * Class to build a station at a given point, names station after nearest city. * If that name is taken then a "Junction" or "Siding" is added to the name. * * @author Luke Lindsay 08-Nov-2002 * * Updated 12th April 2003 by Scott Bennett to include nearest city names. * */
Source code:
/**
* Class to build a station at a given point, names station after nearest city.
* If that name is taken then a "Junction" or "Siding" is added to the name.
*
* @author Luke Lindsay 08-Nov-2002
*
* Updated 12th April 2003 by Scott Bennett to include nearest city names.
*
*/
public class StationBuilder {
private static final Logger logger = Logger.getLogger(StationBuilder.class
.getName());
private int ruleNumber;
private final MoveExecutor executor;
public StationBuilder(MoveExecutor executor) {
this.executor = executor;
TrackRule trackRule;
int i = -1;
ReadOnlyWorld world = executor.getWorld();
do {
i++;
trackRule = (TrackRule) world.get(SKEY.TRACK_RULES, i);
} while (!trackRule.isStation());
ruleNumber = i;
}
public MoveStatus tryBuildingStation(ImPoint p) {
ReadOnlyWorld world = executor.getWorld();
FreerailsPrincipal principal = executor.getPrincipal();
AddStationPreMove preMove = AddStationPreMove.newStation(p,
this.ruleNumber, principal);
Move m = preMove.generateMove(world);
MoveStatus ms = executor.tryDoMove(m);
return ms;
}
public MoveStatus buildStation(ImPoint p) {
// Only build a station if there is track at the specified point.
MoveStatus status = tryBuildingStation(p);
if (status.ok) {
FreerailsPrincipal principal = executor.getPrincipal();
AddStationPreMove preMove = AddStationPreMove.newStation(p,
this.ruleNumber, principal);
return executor.doPreMove(preMove);
}
logger.fine(status.message);
return status;
}
public void setStationType(int ruleNumber) {
this.ruleNumber = ruleNumber;
}
public int getTrackTypeID(String string) {
ReadOnlyWorld w = executor.getWorld();
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule r = (TrackRule) w.get(SKEY.TRACK_RULES, i);
if (string.equals(r.getTypeName())) {
return i;
}
}
throw new NoSuchElementException();
}
}
Methods:
MethodJavadoc
buildStation
getTrackTypeID
setStationType
tryBuildingStation
jfreerails.controller.StockPriceCalculator
Javadoc:
/** * Calculates the stock price for each of the players. * Stock price = [Net worth + 5 * profit last year] / [ shares owned by public + 0.5 shares owned by other players] Let profit last year = 100,000 in the first year. * @author Luke * */
Source code:
/**
* Calculates the stock price for each of the players.
* Stock price = [Net worth + 5 * profit last year] / [ shares owned by public +
0.5 shares owned by other players]
Let profit last year = 100,000 in the first year.
* @author Luke
*
*/
public class StockPriceCalculator {
public static class StockPrice{
public StockPrice(long netWorth, long profitLastyear, int publicShares, int otherRRShares){
currentPrice = calStockPrice(netWorth, profitLastyear, publicShares, otherRRShares);
sellPrice = calStockPrice(netWorth, profitLastyear, publicShares + STOCK_BUNDLE_SIZE, otherRRShares - STOCK_BUNDLE_SIZE);
buyPrice = calStockPrice(netWorth, profitLastyear, publicShares - STOCK_BUNDLE_SIZE, otherRRShares + STOCK_BUNDLE_SIZE);
treasurySellPrice = calStockPrice(netWorth, profitLastyear, publicShares + STOCK_BUNDLE_SIZE, otherRRShares);
treasuryBuyPrice = calStockPrice(netWorth, profitLastyear, publicShares - STOCK_BUNDLE_SIZE, otherRRShares);
}
public Money currentPrice;
public Money sellPrice;
public Money buyPrice;
public Money treasuryBuyPrice;
public Money treasurySellPrice;
}
private final ReadOnlyWorld w;
public StockPriceCalculator(ReadOnlyWorld w){
this.w = w;
}
public StockPrice[] calculate() {
StockPrice[] stockPrices = new StockPrice[w.getNumberOfPlayers()];
for (int playerId = 0; playerId < stockPrices.length; playerId++) {
long profitLastYear;
if(isFirstYear(playerId)){
profitLastYear = 100000;
}else{
profitLastYear = profitsLastYear(playerId);
}
long netWorth = netWorth(playerId);
int publicShares = sharesOwnedByPublic(playerId);
int otherRRShares = sharesOwnedByOtherPlayers(playerId);
stockPrices[playerId] = new StockPrice(netWorth, profitLastYear, publicShares, otherRRShares);
}
return stockPrices;
}
/** Returns true if the current time in the same year as the first transaction for the
* specified player.
*/
boolean isFirstYear(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
GameTime firstTransactionTime = w.getTransactionTimeStamp(pr, 0);
GameCalendar calendar = (GameCalendar)w.get(ITEM.CALENDAR);
int year = calendar.getYear(firstTransactionTime.getTicks());
GameTime currentTime = w.currentTime();
int currentYear = calendar.getYear(currentTime.getTicks());
return year == currentYear;
}
/** Returns the players networth at the start of this year.*/
long netWorth(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
NetWorthCalculator nwc = new NetWorthCalculator(w, pr);
//Set the interval to beginning of time to start of this year.
GameCalendar calendar = (GameCalendar)w.get(ITEM.CALENDAR);
GameTime currentTime = w.currentTime();
int currentYear = calendar.getYear(currentTime.getTicks());
int ticksAtStartOfyear = calendar.getTicks(currentYear);
GameTime[] times = {GameTime.BIG_BANG, new GameTime(ticksAtStartOfyear + 1)};
nwc.setTimes(times);
return nwc.calculateValue().getAmount();
}
long profitsLastYear(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
GameCalendar calendar = (GameCalendar)w.get(ITEM.CALENDAR);
GameTime currentTime = w.currentTime();
int currentYear = calendar.getYear(currentTime.getTicks());
int lastyear = currentYear - 1;
int ticksAtStartOfyear = calendar.getTicks(currentYear);
int ticksAtStartOfLastYear = calendar.getTicks(lastyear);
GameTime[] interval = {new GameTime(ticksAtStartOfLastYear), new GameTime(ticksAtStartOfyear)};
TransactionAggregator aggregator = new TransactionAggregator(w, pr){
@Override
protected boolean condition(int transactionID) {
Transaction t = super.w.getTransaction(super.principal,
transactionID);
if (t instanceof AddItemTransaction) {
// Since buying something is just converting one asset type to
// another.
return false;
}
return true;
}
};
aggregator.setTimes(interval);
return aggregator.calculateValue().getAmount();
}
int sharesOwnedByPublic(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
FinancialDataGatherer gatherer = new FinancialDataGatherer(w, pr);
return gatherer.sharesHeldByPublic();
}
int sharesOwnedByOtherPlayers(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
FinancialDataGatherer gatherer = new FinancialDataGatherer(w, pr);
int[] stakes = gatherer.getStockInThisRRs();
int total = 0;
for (int i = 0; i < stakes.length; i++) {
if(i != playerId){
total+= stakes[i];
}
}
return total;
}
static Money calStockPrice(long netWorth, long profitLastyear, int publicShares, int otherRRShares){
if((publicShares + otherRRShares) == 0 ) return new Money(Long.MAX_VALUE);
long price = 2 * (5 * profitLastyear + netWorth) /(2 * publicShares + otherRRShares);
return new Money(price);
}
}
Methods:
MethodJavadoc
calStockPrice
calculate
isFirstYear/** Returns true if the current time in the same year as the first transaction for the
netWorth/** Returns the players networth at the start of this year.*/
profitsLastYear
sharesOwnedByOtherPlayers
sharesOwnedByPublic
jfreerails.controller.TimeTickPreMove
Javadoc:
/** * Generates a TimeTickMove. * * @author Luke * */
Source code:
/**
* Generates a TimeTickMove.
*
* @author Luke
*
*/
@jfreerails.util.InstanceControlled
public class TimeTickPreMove implements PreMove {
private static final long serialVersionUID = 3690479125647208760L;
public static final TimeTickPreMove INSTANCE = new TimeTickPreMove();
private TimeTickPreMove() {
}
public Move generateMove(ReadOnlyWorld w) {
return TimeTickMove.getMove(w);
}
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
}
Methods:
MethodJavadoc
generateMove
readResolve
jfreerails.controller.ToAndFroPathIterator
Javadoc:
/** * Returns a path that goes forwards and backwards along the path passed to its * constructor. * * @author Luke Lindsay 30-Oct-2002 * */
Source code:
/**
* Returns a path that goes forwards and backwards along the path passed to its
* constructor.
*
* @author Luke Lindsay 30-Oct-2002
*
*/
public class ToAndFroPathIterator implements FreerailsPathIterator {
private static final long serialVersionUID = 3256442525337202993L;
private FreerailsPathIterator path;
private boolean forwards = true;
private final List<Point> list;
public ToAndFroPathIterator(List<Point> l) {
list = l;
nextIterator();
}
private void nextIterator() {
path = new FreerailsPathIteratorImpl(list, forwards);
}
public boolean hasNext() {
if (list.size() < 2) {
return false;
}
return true;
}
public void nextSegment(IntLine line) {
if (this.hasNext()) {
if (!path.hasNext()) {
forwards = !forwards;
path = new FreerailsPathIteratorImpl(list, forwards);
}
path.nextSegment(line);
} else {
throw new NoSuchElementException();
}
}
}
Methods:
MethodJavadoc
hasNext
nextIterator
nextSegment
jfreerails.controller.TrackMoveProducer
Javadoc:
/** * Provides methods that generate moves that build, upgrade, and remove track. * * @author Luke */
Source code:
/**
* Provides methods that generate moves that build, upgrade, and remove track.
*
* @author Luke
*/
final public class TrackMoveProducer {
private final ModelRoot mr;
private final MoveExecutor executor;
public enum BuildMode {
BUILD_TRACK, REMOVE_TRACK, UPGRADE_TRACK, IGNORE_TRACK, BUILD_STATION
}
private final Stack<Move> moveStack = new Stack<Move>();
private GameTime lastMoveTime = GameTime.BIG_BANG;
/**
* This generates the transactions - the charge - for the track being built.
*/
private final TrackMoveTransactionsGenerator transactionsGenerator;
public MoveStatus buildTrack(ImPoint from, Step[] path) {
MoveStatus returnValue = MoveStatus.MOVE_OK;
int x = from.x;
int y = from.y;
for (int i = 0; i < path.length; i++) {
returnValue = buildTrack(new ImPoint(x, y), path[i]);
x += path[i].deltaX;
y += path[i].deltaY;
if (!returnValue.ok) {
return returnValue;
}
}
return returnValue;
}
public MoveStatus buildTrack(ImPoint from, Step trackVector) {
ReadOnlyWorld w = executor.getWorld();
FreerailsPrincipal principal = executor.getPrincipal();
switch (getBuildMode()) {
case IGNORE_TRACK: {
return MoveStatus.MOVE_OK;
}
case REMOVE_TRACK: {
try {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateRemoveTrackMove(from, trackVector, w,
principal);
Move moveAndTransaction = transactionsGenerator
.addTransactions(move);
return sendMove(moveAndTransaction);
} catch (Exception e) {
// thrown when there is no track to remove.
// Fix for bug [ 948670 ] Removing non-existent track
return MoveStatus.moveFailed("No track to remove.");
}
}
case BUILD_TRACK:
case UPGRADE_TRACK:
/*
* Do nothing yet since we need to work out what type of track to
* build.
*/
break;
}
assert (getBuildMode() == BuildMode.BUILD_TRACK || getBuildMode() == BuildMode.UPGRADE_TRACK);
int[] ruleIDs = new int[2];
TrackRule[] rules = new TrackRule[2];
int[] xs = { from.x, from.x + trackVector.deltaX };
int[] ys = { from.y, from.y + trackVector.deltaY };
for (int i = 0; i < ruleIDs.length; i++) {
int x = xs[i];
int y = ys[i];
FreerailsTile tile = (FreerailsTile) w.getTile(x, y);
int tt = tile.getTerrainTypeID();
ruleIDs[i] = getBuildTrackStrategy().getRule(tt);
if (ruleIDs[i] == -1) {
TerrainType terrainType = (TerrainType) w.get(
SKEY.TERRAIN_TYPES, tt);
String message = "Non of the selected track types can be built on "
+ terrainType.getDisplayName();
return MoveStatus.moveFailed(message);
}
rules[i] = (TrackRule) w.get(SKEY.TRACK_RULES, ruleIDs[i]);
}
switch (getBuildMode()) {
case UPGRADE_TRACK: {
// upgrade the from tile if necessary.
FreerailsTile tileA = (FreerailsTile) w.getTile(from.x, from.y);
if (tileA.getTrackPiece().getTrackTypeID() != ruleIDs[0] && !isStationHere(from)) {
MoveStatus ms = upgradeTrack(from, ruleIDs[0]);
if (!ms.ok) {
return ms;
}
}
ImPoint point = new ImPoint(from.x + trackVector.getDx(), from.y
+ trackVector.getDy());
FreerailsTile tileB = (FreerailsTile) w.getTile(point.x, point.y);
if (tileB.getTrackPiece().getTrackTypeID() != ruleIDs[1] && !isStationHere(point)) {
MoveStatus ms = upgradeTrack(point, ruleIDs[1]);
if (!ms.ok) {
return ms;
}
}
return MoveStatus.MOVE_OK;
}
case BUILD_TRACK: {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(from, trackVector, rules[0],
rules[1], w, principal);
Move moveAndTransaction = transactionsGenerator
.addTransactions(move);
return sendMove(moveAndTransaction);
}
default:
throw new IllegalArgumentException(String.valueOf(getBuildMode()));
}
}
public MoveStatus upgradeTrack(ImPoint point) {
if (getBuildMode() == BuildMode.UPGRADE_TRACK) {
ReadOnlyWorld w = executor.getWorld();
FreerailsTile tile = (FreerailsTile) w.getTile(point.x, point.y);
int tt = tile.getTerrainTypeID();
return upgradeTrack(point, getBuildTrackStrategy().getRule(tt));
}
throw new IllegalStateException(
"Track builder not set to upgrade track!");
}
public void setTrackBuilderMode(BuildMode i) {
setBuildMode(i);
}
public TrackMoveProducer(MoveExecutor executor, ReadOnlyWorld world, ModelRoot mr) {
if(null == mr) throw new NullPointerException();
this.executor = executor;
this.mr = mr;
FreerailsPrincipal principal = executor.getPrincipal();
transactionsGenerator = new TrackMoveTransactionsGenerator(world,
principal);
setBuildTrackStrategy(BuildTrackStrategy.getDefault(world));
}
public TrackMoveProducer(ModelRoot mr) {
this.executor = mr;
if(null == mr) throw new NullPointerException();
this.mr = mr;
ReadOnlyWorld world = executor.getWorld();
FreerailsPrincipal principal = executor.getPrincipal();
transactionsGenerator = new TrackMoveTransactionsGenerator(world,
principal);
setBuildTrackStrategy(BuildTrackStrategy.getDefault(world));
}
private MoveStatus upgradeTrack(ImPoint point, int trackRuleID) {
ReadOnlyWorld w = executor.getWorld();
TrackPiece before = ((FreerailsTile) w.getTile(point.x, point.y)).getTrackPiece();
/* Check whether there is track here. */
if (before.getTrackTypeID() == NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
return MoveStatus.moveFailed("No track to upgrade.");
}
FreerailsPrincipal principal = executor.getPrincipal();
int owner = ChangeTrackPieceCompositeMove.getOwner(principal, w);
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, trackRuleID);
TrackPiece after = new TrackPieceImpl(before.getTrackConfiguration(),
trackRule, owner, trackRuleID);
/* We don't want to 'upgrade' a station to track. See bug 874416. */
if (before.getTrackRule().isStation()) {
return MoveStatus
.moveFailed("No need to upgrade track at station.");
}
Move move = UpgradeTrackMove.generateMove(before, after, point);
Move move2 = transactionsGenerator.addTransactions(move);
return sendMove(move2);
}
public MoveStatus undoLastTrackMove() {
clearStackIfStale();
if (moveStack.size() > 0) {
Move m = moveStack.pop();
UndoMove undoMove = new UndoMove(m);
MoveStatus ms = executor.doMove(undoMove);
if (!ms.ok) {
return MoveStatus.moveFailed("Can not undo building track!");
}
return ms;
}
return MoveStatus.moveFailed("No track to undo building!");
}
/**
* Moves are only un-doable if no game time has passed since they they were
* executed. This method clears the move stack if the moves were added to
* the stack at a time other than the current time.
*/
private void clearStackIfStale() {
ReadOnlyWorld w = executor.getWorld();
GameTime currentTime = w.currentTime();
if (!currentTime.equals(lastMoveTime)) {
moveStack.clear();
lastMoveTime = currentTime;
}
}
public BuildMode getTrackBuilderMode() {
return getBuildMode();
}
private MoveStatus sendMove(Move m) {
MoveStatus ms = executor.doMove(m);
if (ms.isOk()) {
clearStackIfStale();
moveStack.add(m);
}
return ms;
}
// public BuildTrackStrategy getBuildTrackStrategy() {
// return buildTrackStrategy;
// }
//
// public void setBuildTrackStrategy(BuildTrackStrategy buildTrackStrategy) {
// this.buildTrackStrategy = buildTrackStrategy;
// }
private boolean isStationHere(ImPoint p) {
ReadOnlyWorld w = executor.getWorld();
FreerailsTile tile = (FreerailsTile) w.getTile(p.x, p.y);
return tile.getTrackPiece().getTrackRule().isStation();
}
public void setBuildTrackStrategy(BuildTrackStrategy buildTrackStrategy) {
mr.setProperty(Property.BUILD_TRACK_STRATEGY, buildTrackStrategy);
}
public BuildTrackStrategy getBuildTrackStrategy() {
return (BuildTrackStrategy) mr.getProperty(Property.BUILD_TRACK_STRATEGY);
}
public void setBuildMode(BuildMode buildMode) {
mr.setProperty(Property.TRACK_BUILDER_MODE, buildMode);
}
public BuildMode getBuildMode() {
return (BuildMode) mr.getProperty(Property.TRACK_BUILDER_MODE);
}
}
Methods:
MethodJavadoc
buildTrack
buildTrack
clearStackIfStale/**
getBuildMode
getBuildTrackStrategy
getTrackBuilderMode
isStationHere
sendMove
setBuildMode
setBuildTrackStrategy
setTrackBuilderMode
undoLastTrackMove
upgradeTrack
upgradeTrack
jfreerails.controller.TrackPathFinder
Javadoc:
/** * Finds the best route to build track between two points. * * @author Luke * */
Source code:
/**
* Finds the best route to build track between two points.
*
* @author Luke
*
*/
public class TrackPathFinder implements IncrementalPathFinder {
private static final Logger logger = Logger.getLogger(TrackPathFinder.class
.getName());
private SimpleAStarPathFinder pathFinder = new SimpleAStarPathFinder();
private final ReadOnlyWorld world;
private ImPoint startPoint;
private final FreerailsPrincipal principal;
public TrackPathFinder(ReadOnlyWorld world, FreerailsPrincipal principal) {
this.world = world;
this.principal = principal;
}
public void abandonSearch() {
pathFinder.abandonSearch();
}
private List<ImPoint> convertPath2Points(IntArray path) {
PositionOnTrack progress = new PositionOnTrack();
List<ImPoint> proposedTrack = new ArrayList<ImPoint>();
ImPoint p;
for (int i = 0; i < path.size(); i++) {
progress.setValuesFromInt(path.get(i));
p = new ImPoint(progress.getX(), progress.getY());
proposedTrack.add(p);
logger.fine("Adding point " + p);
}
return proposedTrack;
}
private int[] findTargets(ImPoint targetPoint) {
FreerailsTile tile = (FreerailsTile) world.getTile(targetPoint.x,
targetPoint.y);
TrackPiece trackPiece = tile.getTrackPiece();
int ruleNumber = trackPiece.getTrackTypeID();
int[] targetInts;
if (tile.hasTrack()) {
/*
* If there is already track here, we need to check what directions
* we can build in without creating an illegal track config.
*/
TrackRule trackRule = (TrackRule) world.get(SKEY.TRACK_RULES,
ruleNumber);
/* Count number of possible directions. */
ArrayList<Step> possibleDirections = new ArrayList<Step>();
for (int i = 0; i < 8; i++) {
Step direction = Step.getInstance(i);
TrackConfiguration config = trackPiece.getTrackConfiguration();
TrackConfiguration testConfig = TrackConfiguration.add(config,
direction);
if (trackRule.trackPieceIsLegal(testConfig)) {
possibleDirections.add(direction);
}
}
/* Put them into an array. */
targetInts = new int[possibleDirections.size()];
for (int i = 0; i < targetInts.length; i++) {
Step direction = possibleDirections.get(i);
PositionOnTrack targetPot = PositionOnTrack.createFacing(
targetPoint.x, targetPoint.y, direction);
targetInts[i] = targetPot.toInt();
}
} else {
/* If there is no track here, we can go in any direction. */
targetInts = new int[8];
for (int i = 0; i < 8; i++) {
PositionOnTrack targetPot = PositionOnTrack.createComingFrom(
targetPoint.x, targetPoint.y, Step.getInstance(i));
targetInts[i] = targetPot.toInt();
}
}
return targetInts;
}
public List generatePath(ImPoint start, ImPoint targetPoint,
BuildTrackStrategy bts) throws PathNotFoundException {
setupSearch(start, targetPoint, bts);
pathFinder.search(-1);
IntArray path = pathFinder.retrievePath();
List proposedTrack = convertPath2Points(path);
return proposedTrack;
}
public int getStatus() {
return pathFinder.getStatus();
}
public List<ImPoint> pathAsPoints() {
IntArray path = pathFinder.retrievePath();
return convertPath2Points(path);
}
public Step[] pathAsVectors() {
IntArray path = pathFinder.retrievePath();
int size = path.size();
Step[] vectors = new Step[size];
PositionOnTrack progress = new PositionOnTrack();
int x = startPoint.x;
int y = startPoint.y;
for (int i = 0; i < size; i++) {
progress.setValuesFromInt(path.get(i));
int x2 = progress.getX();
int y2 = progress.getY();
vectors[i] = Step.getInstance(x2 - x, y2 - y);
x = x2;
y = y2;
}
return vectors;
}
public void search(long maxDuration) throws PathNotFoundException {
pathFinder.search(maxDuration);
}
public void setupSearch(ImPoint startPoint, ImPoint targetPoint,
BuildTrackStrategy bts) throws PathNotFoundException {
logger
.fine("Find track path from " + startPoint + " to "
+ targetPoint);
this.startPoint = startPoint;
int[] targetInts = findTargets(targetPoint);
int[] startInts = findTargets(startPoint);
BuildTrackExplorer explorer = new BuildTrackExplorer(world,
principal, startPoint, targetPoint);
explorer.setBuildTrackStrategy(bts);
pathFinder.setupSearch(startInts, targetInts, explorer);
}
}
Methods:
MethodJavadoc
abandonSearch
convertPath2Points
findTargets
generatePath
getStatus/**
pathAsPoints
pathAsVectors
search
setupSearch
jfreerails.controller.TrainAccessor
Javadoc:
/** * Provides convenience methods to access the properties of a train from the * world object. * * @author Luke * */
Source code:
/**
* Provides convenience methods to access the properties of a train from the
* world object.
*
* @author Luke
*
*/
public class TrainAccessor {
private final ReadOnlyWorld w;
private final FreerailsPrincipal p;
private final int id;
public TrainAccessor(final ReadOnlyWorld w, final FreerailsPrincipal p,
final int id) {
this.w = w;
this.p = p;
this.id = id;
}
public int getId() {
return id;
}
public SpeedTimeAndStatus.TrainActivity getStatus(double time){
TrainMotion tm = findCurrentMotion(time);
return tm.getActivity();
}
/**
* Checks the track under the train's final position still exists (i.e.
* has not been bulldozed).
*/
public boolean trackExists() {
ActivityIterator ai = w.getActivities(p, id);
ai.gotoLastActivity();
TrainMotion tm = (TrainMotion) ai.getActivity();
PositionOnTrack pot = tm.getFinalPosition();
int x = pot.getX();
int y = pot.getY();
FreerailsTile tile = (FreerailsTile) w.getTile(x, y);
TrackPiece trackPiece = tile.getTrackPiece();
TrackConfiguration present = trackPiece.getTrackConfiguration();
TrackConfiguration needed = TrackConfiguration.getFlatInstance(pot.cameFrom());
return present.contains(needed);
}
/**
* @return the id of the station the train is currently at, or -1 if no
* current station.
*
*/
public int getStationId(double time){
TrainMotion tm = findCurrentMotion(time);
PositionOnTrack pot = tm.getFinalPosition();
int x = pot.getX();
int y = pot.getY();
//loop thru the station list to check if train is at the same Point
// as
// a station
for (int i = 0; i < w.size(p, KEY.STATIONS); i++) {
StationModel tempPoint = (StationModel) w.get(p, KEY.STATIONS, i);
if (null != tempPoint && (x == tempPoint.x) && (y == tempPoint.y)) {
return i; // train is at the station at location tempPoint
}
}
return -1;
}
public TrainPositionOnMap findPosition(double time) {
ActivityIterator ai = w.getActivities(p, id);
ai.gotoLastActivity();
while (ai.getStartTime() > time && ai.hasPrevious()) {
ai.previousActivity();
}
double dt = time - ai.getStartTime();
dt = Math.min(dt, ai.getDuration());
TrainMotion tm = (TrainMotion) ai.getActivity();
return tm.getState(dt);
}
public TrainMotion findCurrentMotion(double time) {
ActivityIterator ai = w.getActivities(p, id);
ai.gotoLastActivity();
while (ai.getStartTime() > time && ai.hasPrevious()) {
ai.previousActivity();
}
return (TrainMotion) ai.getActivity();
}
public TrainModel getTrain() {
return (TrainModel) w.get(p, KEY.TRAINS, id);
}
public ImmutableSchedule getSchedule() {
TrainModel train = getTrain();
return (ImmutableSchedule) w.get(p, KEY.TRAIN_SCHEDULES, train
.getScheduleID());
}
public ImmutableCargoBundle getCargoBundle() {
TrainModel train = getTrain();
return (ImmutableCargoBundle) w.get(p, KEY.CARGO_BUNDLES, train
.getCargoBundleID());
}
/**
* Returns true iff all the following hold.
* <ol>
* <li>The train is waiting for a full load at some station X.</li>
* <li>The current train order tells the train to goto station X.</li>
* <li>The current train order tells the train to wait for a full load.</li>
* <li>The current train order specifies a consist that matches the train's current consist.</li>
* </ol>
*
*/
public boolean keepWaiting(){
double time = w.currentTime().getTicks();
int stationId = getStationId(time);
if (stationId == -1)
return false;
SpeedTimeAndStatus.TrainActivity act = getStatus(time);
if (act != TrainActivity.WAITING_FOR_FULL_LOAD)
return false;
ImmutableSchedule schedule = getSchedule();
if(schedule.getNumOrders() <1){
//We end up here if all the train orders are deleted while a train
//is waiting for a full load.
return false;
}
TrainOrdersModel order = schedule.getOrder(schedule.getOrderToGoto());
if (order.stationId != stationId)
return false;
if (!order.waitUntilFull)
return false;
TrainModel train = getTrain();
return order.getConsist().equals(train.getConsist());
}
/**
* @return the location of the station the train is currently heading
* towards.
*/
public ImPoint getTarget() {
TrainModel train = (TrainModel) w.get(p, KEY.TRAINS, id);
int scheduleID = train.getScheduleID();
ImmutableSchedule schedule = (ImmutableSchedule) w.get(
p, KEY.TRAIN_SCHEDULES, scheduleID);
int stationNumber = schedule.getStationToGoto();
if (-1 == stationNumber) {
// There are no stations on the schedule.
return new ImPoint(0, 0);
}
StationModel station = (StationModel) w.get(p,
KEY.STATIONS, stationNumber);
return new ImPoint(station.x, station.y);
}
public HashSet<TrackSection> occupiedTrackSection(double time){
TrainMotion tm = findCurrentMotion(time);
PathOnTiles path = tm.getPath();
HashSet<TrackSection> sections = new HashSet<TrackSection>();
ImPoint start = path.getStart();
int x = start.x;
int y = start.y;
for (int i = 0; i < path.steps(); i++) {
Step s = path.getStep(i);
ImPoint tile = new ImPoint(x, y);
x+=s.deltaX;
y+=s.deltaY;
sections.add(new TrackSection(s, tile));
}
return sections;
}
public boolean isMoving(double time){
TrainMotion tm = findCurrentMotion(time);
double speed = tm.getSpeedAtEnd();
return speed != 0;
}
/** The space available on the train measured in cargo units.*/
public ImInts spaceAvailable(){
TrainModel train = (TrainModel) w.get(p, KEY.TRAINS, id);
ImmutableCargoBundle bundleOnTrain = (ImmutableCargoBundle) w.get(p,
KEY.CARGO_BUNDLES, train.getCargoBundleID());
return spaceAvailable2(w, bundleOnTrain, train.getConsist());
}
public static ImInts spaceAvailable2(ReadOnlyWorld row, ImmutableCargoBundle onTrain, ImInts consist){
// This array will store the amount of space available on the train for
// each cargo type.
final int NUM_CARGO_TYPES = row.size(SKEY.CARGO_TYPES);
int[] spaceAvailable = new int[NUM_CARGO_TYPES];
// First calculate the train's total capacity.
for (int j = 0; j < consist.size(); j++) {
int cargoType = consist.get(j);
spaceAvailable[cargoType] += WagonType.UNITS_OF_CARGO_PER_WAGON;
}
for (int cargoType = 0; cargoType < NUM_CARGO_TYPES; cargoType++) {
spaceAvailable[cargoType]= spaceAvailable[cargoType] - onTrain.getAmount(cargoType);
}
return new ImInts(spaceAvailable);
}
}
Methods:
MethodJavadoc
findCurrentMotion
findPosition
getCargoBundle
getId/**
getSchedule
getStationId/**
getStatus
getTarget/**
getTrain
isMoving
keepWaiting/**
occupiedTrackSection
spaceAvailable/** The space available on the train measured in cargo units.*/
spaceAvailable2
trackExists/**
jfreerails.controller.TrainPathIntIterator
Javadoc:
/** * FlatTrackExplorer to FreerailsIntIterator adapter. * * @author Luke Lindsay 30-Nov-2002. * */
Source code:
/**
* FlatTrackExplorer to FreerailsIntIterator adapter.
*
* @author Luke Lindsay 30-Nov-2002.
*
*/
public class TrainPathIntIterator implements FreerailsIntIterator {
private final FlatTrackExplorer trackExplorer;
public TrainPathIntIterator(FlatTrackExplorer t) {
trackExplorer = t;
}
public boolean hasNextInt() {
return trackExplorer.hasNextEdge();
}
public int nextInt() {
trackExplorer.nextEdge();
trackExplorer.moveForward();
return trackExplorer.getPosition();
}
}
Methods:
MethodJavadoc
hasNextInt
nextInt
jfreerails.controller.TrainStopsHandler
Javadoc:
/** * @author Luke * */
Source code:
/**
* @author Luke
*
*/
public class TrainStopsHandler implements Serializable {
private static final Logger logger = Logger.getLogger(TrainStopsHandler.class.getName());
private static final int NOT_AT_STATION = -1;
private static final long serialVersionUID = 3257567287094882872L;
/** If wagons are added to a train, we need to increase its length.*/
static PathOnTiles lengthenPath(ReadOnlyWorld w, PathOnTiles path, int currentTrainLength) {
double pathDistance = path.getTotalDistance();
double extraDistanceNeeded = currentTrainLength - pathDistance;
List<Step> steps = new ArrayList<Step>();
ImPoint start = path.getStart();
Step firstStep = path.getStep(0);
PositionOnTrack nextPot = PositionOnTrack.createComingFrom(start.x, start.y, firstStep);
while( extraDistanceNeeded > 0){
FlatTrackExplorer fte = new FlatTrackExplorer(w, nextPot);
fte.nextEdge();
nextPot.setValuesFromInt(fte.getVertexConnectedByEdge());
Step cameFrom = nextPot.facing();
steps.add(0, cameFrom);
extraDistanceNeeded -= cameFrom.getLength();
}
//Add existing steps
for (int i = 0; i < path.steps(); i++) {
Step step = path.getStep(i);
steps.add(step);
}
ImPoint newStart = new ImPoint(nextPot.getX(), nextPot.getY());
path = new PathOnTiles(newStart, steps);
return path;
}
private final FreerailsPrincipal principal;
private GameTime timeLoadingFinished = new GameTime(0);
private final int trainId;
private final WorldDiffs worldDiffs;
public TrainStopsHandler(int id, FreerailsPrincipal p, WorldDiffs w) {
trainId = id;
principal = p;
worldDiffs = w;
}
public ImPoint arrivesAtPoint(int x, int y) {
TrainAccessor ta = new TrainAccessor(worldDiffs, principal, trainId);
ImPoint targetPoint = ta.getTarget();
if (x == targetPoint.x && y == targetPoint.y) {
updateTarget();
targetPoint = ta.getTarget();
} else {
int stationNumber = getStationID(x, y);
if (NOT_AT_STATION != stationNumber) {
loadAndUnloadCargo(stationNumber, false, false);
}
}
return targetPoint;
}
public Move getMoves() {
Move m = WorldDiffMove.generate(worldDiffs, WorldDiffMove.Cause.TrainArrives);
worldDiffs.reset();
return m;
}
/**
* @return the number of the station the train is currently at, or -1 if no
* current station.
*/
public int getStationID(int x, int y) {
// loop thru the station list to check if train is at the same Point
// as
// a station
for (int i = 0; i < worldDiffs.size(principal, KEY.STATIONS); i++) {
StationModel tempPoint = (StationModel) worldDiffs.get(principal, KEY.STATIONS, i);
if (null != tempPoint && (x == tempPoint.x) && (y == tempPoint.y)) {
return i; // train is at the station at location tempPoint
}
}
return -1;
// there are no stations that exist where the train is currently
}
public int getTrainLength() {
TrainAccessor ta = new TrainAccessor(worldDiffs, principal, trainId);
return ta.getTrain().getLength();
}
public boolean isTrainFull() {
TrainAccessor train = new TrainAccessor(worldDiffs, principal, trainId);
ImInts spaceAvailable = train.spaceAvailable();
return spaceAvailable.sum() == 0;
}
public boolean isTrainMoving() {
if (refreshWaitingForFullLoad()) {
return false;
}
GameTime time = worldDiffs.currentTime();
return time.getTicks() > this.timeLoadingFinished.getTicks();
}
public boolean isWaiting4FullLoad() {
TrainModel train = (TrainModel) worldDiffs.get(principal, KEY.TRAINS, this.trainId);
int scheduleID = train.getScheduleID();
ImmutableSchedule schedule = (ImmutableSchedule) worldDiffs.get(principal,
KEY.TRAIN_SCHEDULES, scheduleID);
if(schedule.getNumOrders() == 0){
return false;
}
TrainOrdersModel order = schedule.getOrder(schedule.getOrderToGoto());
return !isTrainFull() && order.waitUntilFull;
}
void loadAndUnloadCargo(int stationId, boolean waiting, boolean autoConsist) {
// train is at a station so do the cargo processing
DropOffAndPickupCargoMoveGenerator transfer = new DropOffAndPickupCargoMoveGenerator(
trainId, stationId, worldDiffs, principal, waiting, autoConsist);
Move m = transfer.generateMove();
if(null != m){
MoveStatus ms = m.doMove(worldDiffs, principal);
if (!ms.ok)
throw new IllegalStateException(ms.message);
}
}
void makeTrainWait(int ticks) {
GameTime currentTime = worldDiffs.currentTime();
timeLoadingFinished = new GameTime(currentTime.getTicks() + ticks);
}
public boolean refreshWaitingForFullLoad() {
TrainAccessor ta = new TrainAccessor(worldDiffs, principal, trainId);
ImmutableSchedule schedule = ta.getSchedule();
int stationId = ta.getStationId(Double.MAX_VALUE);
if(stationId<0) throw new IllegalStateException();
//The train's orders may have changed...
final int orderToGoto = schedule.getOrderToGoto();
if(-1 == orderToGoto){
//We end up here if all the orders are deleted.
return false;
}
TrainOrdersModel order = schedule.getOrder(orderToGoto);
//Should we go to another station?
if(stationId != order.stationId){
return false;
}
//Should we change the consist?
ImInts consist = ta.getTrain().getConsist();
if(!consist.equals(order.consist)){
// ..if so, we should change the consist.
int oldLength = ta.getTrain().getLength();
int engineType = ta.getTrain().getEngineType();
TrainModel newTrain = ta.getTrain().getNewInstance(engineType, order.consist);
worldDiffs.set(principal, KEY.TRAINS, trainId, newTrain);
int newLength = newTrain.getLength();
//has the trains length increased?
if(newLength > oldLength){
TrainMotion tm = ta.findCurrentMotion(Double.MAX_VALUE);
PathOnTiles path = tm.getPath();
path = lengthenPath(worldDiffs, path, oldLength);
SpeedTimeAndStatus.TrainActivity status = isWaiting4FullLoad() ? WAITING_FOR_FULL_LOAD : STOPPED_AT_STATION;
TrainMotion nextMotion = new TrainMotion(path, newLength,
0, status);
// Create a new Move object.
Move trainMove = new NextActivityMove(nextMotion, trainId,
principal);
MoveStatus ms = trainMove.doMove(worldDiffs, Player.AUTHORITATIVE);
if(!ms.ok) throw new IllegalStateException(ms.message);
}
}
/* Add any cargo that is waiting. */
loadAndUnloadCargo(schedule.getStationToGoto(), order.waitUntilFull, order.autoConsist);
//Should we stop waiting?
if(!order.waitUntilFull){
updateSchedule();
return false;
}
if (isTrainFull()) {
updateSchedule();
return false;
}
return true;
}
private void scheduledStop() {
TrainModel train = (TrainModel) worldDiffs.get(principal, KEY.TRAINS, this.trainId);
Schedule schedule = (ImmutableSchedule) worldDiffs.get(principal, KEY.TRAIN_SCHEDULES,
train.getScheduleID());
ImInts wagonsToAdd = schedule.getWagonsToAdd();
// Loading and unloading cargo takes time, so we make the train wait for
// a few ticks.
makeTrainWait(50);
boolean autoConsist = schedule.autoConsist();
if (null != wagonsToAdd) {
int engine = train.getEngineType();
Move m = ChangeTrainMove.generateMove(this.trainId, train, engine, wagonsToAdd,
principal);
m.doMove(worldDiffs, principal);
}
updateSchedule();
int stationToGoto = schedule.getStationToGoto();
loadAndUnloadCargo(stationToGoto, true, autoConsist);
}
void updateSchedule() {
TrainModel train = (TrainModel) worldDiffs.get(principal, KEY.TRAINS, this.trainId);
int scheduleID = train.getScheduleID();
ImmutableSchedule currentSchedule = (ImmutableSchedule) worldDiffs.get(principal,
KEY.TRAIN_SCHEDULES, scheduleID);
MutableSchedule schedule = new MutableSchedule(currentSchedule);
StationModel station = null;
TrainOrdersModel order = schedule.getOrder(schedule.getOrderToGoto());
boolean waiting4FullLoad = order.waitUntilFull && !isTrainFull();
if (!waiting4FullLoad) {
schedule.gotoNextStation();
ImmutableSchedule newSchedule = schedule.toImmutableSchedule();
worldDiffs.set(principal, KEY.TRAIN_SCHEDULES, scheduleID, newSchedule);
int stationNumber = schedule.getStationToGoto();
station = (StationModel) worldDiffs.get(principal, KEY.STATIONS, stationNumber);
if (null == station) {
logger.warning("null == station, train " + trainId
+ " doesn't know where to go next!");
}
}
}
/**
* Issues a ChangeTrainScheduleMove to set the train to move to the next
* station.
*/
public void updateTarget() {
scheduledStop();
}
}
Methods:
MethodJavadoc
arrivesAtPoint
getMoves
getStationID/**
getTrainLength
isTrainFull
isTrainMoving
isWaiting4FullLoad
lengthenPath/** If wagons are added to a train, we need to increase its length.*/
loadAndUnloadCargo
makeTrainWait
refreshWaitingForFullLoad
scheduledStop
updateSchedule
updateTarget/**
jfreerails.controller.UnexpectedExceptionForm
Javadoc:
/** * * @author Luke */
Source code:
/**
*
* @author Luke
*/
public class UnexpectedExceptionForm extends javax.swing.JFrame {
private static final long serialVersionUID = -4348641764811196495L;
/** Creates new form UnexpectedExceptionForm */
public UnexpectedExceptionForm() {
initComponents();
}
public void setText(String s){
copyableTextJPanel1.setText(s);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
copyableTextJPanel1 = new jfreerails.controller.CopyableTextJPanel();
closebutton = new javax.swing.JButton();
getContentPane().setLayout(new java.awt.GridBagLayout());
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Unexpected Exception");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(copyableTextJPanel1, gridBagConstraints);
closebutton.setText("Close");
closebutton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closebuttonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
getContentPane().add(closebutton, gridBagConstraints);
pack();
}
// </editor-fold>//GEN-END:initComponents
private void closebuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closebuttonActionPerformed
System.exit(1);
}//GEN-LAST:event_closebuttonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
UnexpectedExceptionForm unexpectedExceptionForm = new UnexpectedExceptionForm();
Exception e = new Exception("Oh No..");
String str = ReportBugTextGenerator.genText(e);
unexpectedExceptionForm.setText(str);
unexpectedExceptionForm.setVisible(true);
e.printStackTrace();
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JButton closebutton;
jfreerails.controller.CopyableTextJPanel copyableTextJPanel1;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
closebuttonActionPerformed
initComponents/** This method is called from within the constructor to
main/**
setText
jfreerails.controller.VerifyStationName
Javadoc:
/** * Class to verify that the chosen name for a station hasn't already been taken * by another station. If the name has been used, a minor alteration in the name * is required, by adding perhaps "Junction" or "Siding" to the name. * * @author Scott Bennett * * Date: 12th April 2003 * */
Source code:
/**
* Class to verify that the chosen name for a station hasn't already been taken
* by another station. If the name has been used, a minor alteration in the name
* is required, by adding perhaps "Junction" or "Siding" to the name.
*
* @author Scott Bennett
*
* Date: 12th April 2003
*
*/
public class VerifyStationName {
private final ReadOnlyWorld w;
private final String nameToVerify;
private final Vector<String> stationAlternatives;
public VerifyStationName(ReadOnlyWorld world, String name) {
this.w = world;
this.nameToVerify = name;
this.stationAlternatives = new Vector<String>();
stationAlternatives.addElement("Junction");
stationAlternatives.addElement("Siding");
stationAlternatives.addElement("North");
stationAlternatives.addElement("East");
stationAlternatives.addElement("South");
stationAlternatives.addElement("West");
}
public String getName() {
String appropriateName = nameToVerify;
boolean found = false;
String tempName = null;
// if (w.size(KEY.STATIONS) <= 0) {
// //if there are no stations, then obviously the name isn't taken
// return appropriateName;
// }
found = checkStationExists(appropriateName);
if (!found) {
return appropriateName;
}
// a station with that name already exists, so we need to find another
// name
for (int i = 0; i < stationAlternatives.size(); i++) {
tempName = appropriateName + " " + stationAlternatives.elementAt(i);
found = checkStationExists(tempName);
if (!found) {
return tempName;
}
}
int j = 7; // for number of names that have already been used
while (found) {
j++;
tempName = appropriateName + "Station #" + j;
found = checkStationExists(tempName);
}
return tempName;
}
private boolean checkStationExists(String name) {
String testName = name;
StationModel tempStation;
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
while (wi.next()) { // loop over non null stations
tempStation = (StationModel) wi.getElement();
if ((testName).equals(tempStation.getStationName())) {
// station already exists with that name
return true;
}
}
}
// no stations exist with that name
return false;
}
}
Methods:
MethodJavadoc
checkStationExists
getName
jfreerails.launcher.ClientOptionsJPanel
Javadoc:
/** * The Launcher panel that lets you choose fullscreen or windowed mode and the * screen resolution etc. * * @author rtuck99@users.sourceforge.net * @author Luke Lindsay */
Source code:
/**
* The Launcher panel that lets you choose fullscreen or windowed mode and the
* screen resolution etc.
*
* @author rtuck99@users.sourceforge.net
* @author Luke Lindsay
*/
class ClientOptionsJPanel extends javax.swing.JPanel implements LauncherPanel {
private static final long serialVersionUID = 3256721779883325748L;
private static final Logger logger = Logger
.getLogger(ClientOptionsJPanel.class.getName());
private final LauncherInterface owner;
private String[] names;
private static final String INVALID_PORT = "A valid port value is between between 0 and 65535.";
private final DocumentListener documentListener = new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
validateInput();
}
public void removeUpdate(DocumentEvent e) {
validateInput();
}
public void changedUpdate(DocumentEvent e) {
validateInput();
}
};
/**
* If the user has opted to load a game, we need to limit the list of
* players to participants in the game we are loading. Otherwise, any player
* name is OK. Either, pass in a array of names or null if any name is OK.
*/
void limitPlayerNames(String[] n) {
this.names = n;
if (names == null) {
playerName.setVisible(true);
playerNames.setVisible(false);
playerName.setEditable(true);
} else {
if (names.length == 1) {
playerName.setVisible(true);
playerNames.setVisible(false);
playerName.setText(n[0]);
playerName.setEditable(false);
} else {
playerName.setVisible(false);
playerNames.setVisible(true);
ComboBoxModel model = new DefaultComboBoxModel(names);
playerNames.setModel(model);
}
}
this.revalidate();
}
String getPlayerName() {
if (playerName.isVisible()) {
return playerName.getText();
}
int index = playerNames.getSelectedIndex();
if (index < 0)
return null; // no selection.
return names[index];
}
DisplayMode getDisplayMode() {
if (this.fullScreenButton.isSelected()) {
MyDisplayMode displayMode = ((MyDisplayMode) jList1
.getSelectedValue());
logger.fine("The selected display mode is "
+ displayMode.toString());
return displayMode.displayMode;
}
return null;
}
InetSocketAddress getRemoteServerAddress() {
String portStr = remotePort.getText();
if (portStr == null) {
return null;
}
int port;
try {
port = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
return null;
}
InetSocketAddress address;
try {
address = new InetSocketAddress(remoteIP.getText(), port);
} catch (IllegalArgumentException e) {
return null;
}
/*
* cut and pasted InetSocketAddress isa = getRemoteServerAddress(); if
* (isa == null) { infoText = "Please enter a valid remote server
* address"; } else if (isa.isUnresolved()) { infoText = "Couldn't
* resolve remote server address"; } else { isValid = true; }
*/
return address;
}
public boolean validateInput() {
/* Validate player name. */
if (playerName.getText() == null || playerName.getText().equals("")) {
owner.setInfoText("Please set a name for your player",
LauncherInterface.ERROR);
return false;
}
/* Validate host name. */
if (remoteIP.getText() == null || remoteIP.getText().equals("")) {
owner.setInfoText("Please enter a host name",
LauncherInterface.ERROR);
return false;
}
/* Validate port. */
try {
int port = Integer.parseInt(remotePort.getText());
if (port < 0 || port > 65535) {
owner.setInfoText(INVALID_PORT, LauncherInterface.ERROR);
return false;
}
} catch (Exception e) {
owner.setInfoText(INVALID_PORT, LauncherInterface.ERROR);
return false;
}
/*
* Validate display-mode selection. Note, on some systems the display
* mode can't be changed, in which case the list of selectable display
* modes will have length 0.
*/
if (fullScreenButton.isSelected() && jList1.getModel().getSize() > 0
&& jList1.getSelectedIndex() == -1) {
owner
.setInfoText("Select a display-mode.",
LauncherInterface.ERROR);
return false;
}
/* Everything is ok. */
owner.hideErrorMessages();
owner.setProperty("freerails.server.port", this.remotePort.getText());
owner.setProperty("freerails.player.name", this.playerName.getText());
owner.setProperty("freerails.server.ip.address", this.remoteIP.getText());
owner.saveProps();
return true;
}
int getScreenMode() {
if (this.fullScreenButton.isSelected()) {
return ScreenHandler.FULL_SCREEN;
} else if (this.windowedButton.isSelected()) {
return ScreenHandler.WINDOWED_MODE;
} else if (this.fixedSizeButton.isSelected()) {
return ScreenHandler.FIXED_SIZE_WINDOWED_MODE;
} else {
throw new IllegalStateException();
}
}
public void setControlsEnabled(boolean enabled) {
windowedButton.setEnabled(enabled);
fullScreenButton.setEnabled(enabled);
fixedSizeButton.setEnabled(enabled);
if (fullScreenButton.isSelected()) {
jList1.setEnabled(enabled);
}
}
private final DisplayModesComboBoxModels listModel;
void setRemoteServerPanelVisible(boolean b) {
this.jPanel4.setVisible(b);
}
public ClientOptionsJPanel(LauncherInterface owner) {
this.owner = owner;
initComponents();
listModel = new DisplayModesComboBoxModels();
listModel.removeDisplayModesBelow(640, 480, 16);
jList1.setModel(listModel);
jList1.setSelectedIndex(0);
validateInput();
// Listen for changes in the server port text box.
remotePort.getDocument().addDocumentListener(documentListener);
remoteIP.getDocument().addDocumentListener(documentListener);
playerName.getDocument().addDocumentListener(documentListener);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel3 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
playerName = new javax.swing.JTextField();
playerNames = new javax.swing.JComboBox();
jPanel4 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
remoteIP = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
remotePort = new javax.swing.JTextField();
spacer = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jPanel2 = new javax.swing.JPanel();
windowedButton = new javax.swing.JRadioButton();
fixedSizeButton = new javax.swing.JRadioButton();
fullScreenButton = new javax.swing.JRadioButton();
setLayout(new java.awt.GridBagLayout());
addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
jPanel3.setBorder(new javax.swing.border.TitledBorder(
new javax.swing.border.EtchedBorder(), "Player Details"));
jLabel1.setText("Player name:");
jPanel3.add(jLabel1);
playerName.setColumns(12);
playerName.setText(owner.getProperty("freerails.player.name"));
jPanel3.add(playerName);
playerNames.setToolTipText("Select a player from the saved game.");
jPanel3.add(playerNames);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
add(jPanel3, gridBagConstraints);
jPanel4.setLayout(new java.awt.GridBagLayout());
jPanel4
.setBorder(new javax.swing.border.TitledBorder(
new javax.swing.border.EtchedBorder(),
"Remote server address"));
jPanel4.setEnabled(false);
jLabel2.setText("IP Address:");
jPanel4.add(jLabel2, new java.awt.GridBagConstraints());
remoteIP.setColumns(15);
remoteIP.setText(owner.getProperty("freerails.server.ip.address"));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel4.add(remoteIP, gridBagConstraints);
jLabel3.setText("port");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel4.add(jLabel3, gridBagConstraints);
remotePort.setColumns(5);
remotePort.setText(owner.getProperty("freerails.server.port"));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel4.add(remotePort, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
jPanel4.add(spacer, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
add(jPanel4, gridBagConstraints);
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel1.setBorder(new javax.swing.border.TitledBorder(
new javax.swing.border.EtchedBorder(), "Select Display Mode"));
jScrollPane1.setBorder(new javax.swing.border.BevelBorder(
javax.swing.border.BevelBorder.LOWERED));
jList1
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.setEnabled(false);
jList1
.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(
javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jScrollPane1.setViewportView(jList1);
jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);
jPanel2.setLayout(new javax.swing.BoxLayout(jPanel2,
javax.swing.BoxLayout.Y_AXIS));
buttonGroup1.add(windowedButton);
windowedButton.setSelected(true);
windowedButton.setText("Windowed");
jPanel2.add(windowedButton);
buttonGroup1.add(fixedSizeButton);
fixedSizeButton.setText("Windowed (fixed size 640*480)");
jPanel2.add(fixedSizeButton);
buttonGroup1.add(fullScreenButton);
fullScreenButton.setText("Full screen");
fullScreenButton
.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
fullScreenButtonStateChanged(evt);
}
});
jPanel2.add(fullScreenButton);
jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jPanel1, gridBagConstraints);
}// GEN-END:initComponents
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {// GEN-FIRST:event_jList1ValueChanged
validateInput();
}// GEN-LAST:event_jList1ValueChanged
private void formComponentShown(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_formComponentShown
validateInput();
}// GEN-LAST:event_formComponentShown
private void fullScreenButtonStateChanged(javax.swing.event.ChangeEvent evt) {// GEN-FIRST:event_fullScreenButtonStateChanged
jList1.setEnabled(fullScreenButton.isSelected());
validateInput();
}// GEN-LAST:event_fullScreenButtonStateChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.ButtonGroup buttonGroup1;
javax.swing.JRadioButton fixedSizeButton;
javax.swing.JRadioButton fullScreenButton;
javax.swing.JLabel jLabel1;
javax.swing.JLabel jLabel2;
javax.swing.JLabel jLabel3;
javax.swing.JList jList1;
javax.swing.JPanel jPanel1;
javax.swing.JPanel jPanel2;
javax.swing.JPanel jPanel3;
javax.swing.JPanel jPanel4;
javax.swing.JScrollPane jScrollPane1;
javax.swing.JTextField playerName;
javax.swing.JComboBox playerNames;
javax.swing.JTextField remoteIP;
javax.swing.JTextField remotePort;
javax.swing.JPanel spacer;
javax.swing.JRadioButton windowedButton;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
formComponentShown
fullScreenButtonStateChanged
getDisplayMode
getPlayerName
getRemoteServerAddress
getScreenMode
initComponents/**
jList1ValueChanged
limitPlayerNames/**
setControlsEnabled
setRemoteServerPanelVisible
validateInput
jfreerails.launcher.ConnectedPlayersJPanel
Javadoc:
/** * A JPanel that shows the players currently logged in to the server. * * @author Luke */
Source code:
/**
* A JPanel that shows the players currently logged in to the server.
*
* @author Luke
*/
public class ConnectedPlayersJPanel extends javax.swing.JPanel implements
PropertyChangeListener {
private static final long serialVersionUID = 4049080453489111344L;
FreerailsGameServer server = null;
/** Creates new form ConnectedPlayersJPanel */
public ConnectedPlayersJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
title = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
setLayout(new java.awt.GridBagLayout());
title.setText("Connected Players");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(title, gridBagConstraints);
jList1.setModel(new javax.swing.AbstractListModel() {
private static final long serialVersionUID = 1L;
String[] strings = { "No players are logged on!" };
public int getSize() {
return strings.length;
}
public Object getElementAt(int i) {
return strings[i];
}
});
jScrollPane1.setViewportView(jList1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}// GEN-END:initComponents
void updateListOfPlayers() {
if (null != server) {
String[] playerNames = server.getPlayerNames();
playerNames = playerNames.length == 0 ? new String[] { "No players are logged on!" }
: playerNames;
setListOfPlayers(playerNames);
}
}
void setListOfPlayers(String[] players) {
jList1.setListData(players);
}
/** Called by the server when a player is added or removed. */
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(FreerailsGameServer.CONNECTED_PLAYERS)) {
if (EventQueue.isDispatchThread()) {
updateListOfPlayers();
} else {
EventQueue.invokeLater(new Runnable() {
public void run() {
updateListOfPlayers();
}
});
}
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JList jList1;
javax.swing.JScrollPane jScrollPane1;
javax.swing.JLabel title;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
initComponents/**
propertyChange/** Called by the server when a player is added or removed. */
setListOfPlayers
updateListOfPlayers
jfreerails.launcher.GUIClient
Javadoc:
/** * A swing freerails client. * * @author Luke * */
Source code:
/**
* A swing freerails client.
*
* @author Luke
*
*/
public class GUIClient extends FreerailsClient implements
FreerailsProgressMonitor {
public static void main(String[] args) {
try {
GUIClient client = new GUIClient("Test", null,
ScreenHandler.WINDOWED_MODE, null);
client.start();
} catch (IOException e) {
e.printStackTrace();
}
}
private final ActionRoot actionRoot;
private final GUIComponentFactoryImpl factory;
private final ModelRootImpl modelRoot;
private final FreerailsProgressMonitor monitor;
private final String name;
private final ScreenHandler screenHandler;
private RenderersRoot vl;
public GUIClient(String name, FreerailsProgressMonitor fm, int screenMode,
DisplayMode dm) throws IOException {
this.name = name;
this.monitor = null == fm ? this : fm;
// Set up model root and action root.
modelRoot = new ModelRootImpl();
modelRoot.setMoveFork(this.getMoveFork());
modelRoot.setMoveReceiver(this);
modelRoot.setServerCommandReceiver(this);
actionRoot = new ActionRoot(modelRoot);
// Create GUI components
factory = new GUIComponentFactoryImpl(modelRoot, actionRoot);
JFrame createClientJFrame = factory.createClientJFrame(name);
screenHandler = new ScreenHandler(createClientJFrame, screenMode, dm);
}
@Override
protected void clientUpdates() {
if (factory.isSetup()) {
factory.getBuildTrackController().update();
// Update sub tick time.
long currentTime = System.currentTimeMillis();
long lastTick = getLastTickTime();
double dt = currentTime - lastTick;
ReadOnlyWorld world2 = modelRoot.getWorld();
GameSpeed gameSpeed = (GameSpeed) world2.get(ITEM.GAME_SPEED);
GameTime currentGameTime = world2.currentTime();
double ticks = currentGameTime.getTicks();
if(!gameSpeed.isPaused()){
double milliSecondsPerTick = 1000/ gameSpeed.getSpeed();
double subTicks = dt / milliSecondsPerTick;
subTicks = Math.min(dt, 1d);
ticks += subTicks;
}
modelRoot.setProperty(Property.TIME, new Double(ticks));
}
}
public void finished() {
// TODO Auto-generated method stub
}
public ScreenHandler getScreenHandler() {
return screenHandler;
}
@Override
protected void newWorld(World w) {
try {
if (null == vl || !vl.validate(w)) {
try {
vl = new RenderersRootImpl(w, monitor);
monitor.finished();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Should be a smarter way of doing this..
for (int player = 0; player < w.getNumberOfPlayers(); player++) {
Player p = w.getPlayer(player);
if (p.getName().equals(this.name)) {
modelRoot.setup(w, p.getPrincipal());
}
}
modelRoot.setProperty(ModelRoot.Property.SERVER, connection2Server
.getServerDetails());
actionRoot.setup(modelRoot, vl);
factory.setup(vl, w);
} catch (Exception e) {
ReportBugTextGenerator.unexpectedException(e);
}
}
public void nextStep(int max) {
// TODO Auto-generated method stub
}
public void setMessage(String s) {
System.out.println(s);
}
public void setValue(int i) {
// TODO Auto-generated method stub
}
@Override
public void setProperty(ClientProperty propertyName, Serializable value) {
super.setProperty(propertyName, value);
switch (propertyName) {
case SAVED_GAMES:
modelRoot.setProperty(Property.SAVED_GAMES_LIST, value);
break;
default:
break;
}
}
void start() {
// Set up world.
SavedGamesManager gamesManager = new SavedGamesManagerImpl();
FreerailsGameServer server = new FreerailsGameServer(gamesManager);
String mapName = gamesManager.getNewMapNames()[0];
ServerGameModelImpl serverGameModel = new ServerGameModelImpl();
server.setServerGameModel(serverGameModel);
this.connect(server, name, "password");
server.newGame(mapName);
while (null == this.getWorld()) {
this.update();
server.update();
}
GameModel[] models = new GameModel[] { this, server };
// Start the game loop
GameLoop gameLoop = new GameLoop(screenHandler, models);
Thread t = new Thread(gameLoop);
t.start();
}
}
Methods:
MethodJavadoc
clientUpdates
finished
getScreenHandler
main
newWorld
nextStep
setMessage
setProperty
setValue
start/**
jfreerails.launcher.Launcher
Javadoc:
/** * Launcher GUI for both the server and/or client. * * TODO The code in the switch statements needs reviewing. * * @author rtuck99@users.sourceforge.net * @author Luke */
Source code:
/**
* Launcher GUI for both the server and/or client.
*
* TODO The code in the switch statements needs reviewing.
*
* @author rtuck99@users.sourceforge.net
* @author Luke
*/
public class Launcher extends javax.swing.JFrame implements LauncherInterface {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(Launcher.class
.getName());
private static String QUICKSTART = "-quickstart";
private final Component[] wizardPages = new Component[4];
private int currentPage = 0;
private FreerailsGameServer server;
private GUIClient client;
private Properties props;
private final ImageIcon errorIcon = new javax.swing.ImageIcon(getClass()
.getResource("/jfreerails/client/graphics/icons/error.gif"));
private final ImageIcon warningIcon = new javax.swing.ImageIcon(getClass()
.getResource("/jfreerails/client/graphics/icons/warning.gif"));
private final ImageIcon infoIcon = new javax.swing.ImageIcon(getClass()
.getResource("/jfreerails/client/graphics/icons/info.gif"));
private final ProgressJPanel progressPanel = new ProgressJPanel(this);
public void setNextEnabled(boolean enabled) {
nextButton.setEnabled(enabled);
if (nextIsStart) {
nextButton.setText("Start");
} else {
nextButton.setText("Next...");
}
}
private boolean nextIsStart = false;
private void startGame() {
CardLayout cl = (CardLayout) jPanel1.getLayout();
cl.show(jPanel1, "4");
setButtonsVisible(false);
LauncherPanel1 lp = (LauncherPanel1) wizardPages[0];
SelectMapJPanel msp = (SelectMapJPanel) wizardPages[1];
ClientOptionsJPanel cop = (ClientOptionsJPanel) wizardPages[2];
ConnectedPlayersJPanel cp = (ConnectedPlayersJPanel) wizardPages[3];
boolean recover = false;
int mode;
switch (lp.getMode()) {
case LauncherPanel1.MODE_SINGLE_PLAYER:
try {
mode = cop.getScreenMode();
client = new GUIClient(cop.getPlayerName(), progressPanel,
mode, cop.getDisplayMode());
if (isNewGame()) {
initServer();
}
client.connect(server, cop.getPlayerName(), "password");
setServerGameModel();
} catch (IOException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} finally {
if (recover) {
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setButtonsVisible(true);
currentPage = 1;
cl.show(jPanel1, "1");
return;
}
}
startThread(server, client);
break;
case LauncherPanel1.MODE_START_NETWORK_GAME:
// LL: I don't think this code ever executes now that there is a
// connected players screen.
try {
setServerGameModel();
currentPage = 3;
String[] playerNames = server.getPlayerNames();
playerNames = playerNames.length == 0 ? new String[] { "No players are connected." }
: playerNames;
cp.setListOfPlayers(playerNames);
cl.show(jPanel1, "3");
setNextEnabled(false);
} catch (IOException e) {
// We end up here if an Exception was thrown when loading a
// saved game.
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} finally {
if (recover) {
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setNextEnabled(true);
currentPage = 1;
setButtonsVisible(true);
cl.show(jPanel1, "1");
return;
}
}
break;
case LauncherPanel1.MODE_JOIN_NETWORK_GAME:
mode = cop.getScreenMode();
try {
InetSocketAddress serverInetAddress = cop
.getRemoteServerAddress();
if (null == serverInetAddress) {
throw new NullPointerException("Couldn't resolve hostname.");
}
String playerName = cop.getPlayerName();
client = new GUIClient(playerName, progressPanel, mode, cop
.getDisplayMode());
String hostname = serverInetAddress.getHostName();
int port = serverInetAddress.getPort();
setInfoText("Connecting to server...", LauncherInterface.INFO);
LogOnResponse logOnResponse = client.connect(hostname, port,
playerName, "password");
if (logOnResponse.isSuccessful()) {
setInfoText("Logged on and waiting for game to start.", LauncherInterface.INFO);
startThread(client);
} else {
recover = true;
setInfoText(logOnResponse.getMessage(),
LauncherInterface.WARNING);
}
} catch (IOException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} catch (NullPointerException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} finally {
if (recover) {
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setButtonsVisible(true);
cl.show(jPanel1, "2");
return;
}
}
break;
case LauncherPanel1.MODE_SERVER_ONLY:
if (msp.validateInput()) {
initServer();
try {
setServerGameModel();
prepare2HostNetworkGame(msp.getServerPort());
setNextEnabled(true);
} catch (NullPointerException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} catch (IOException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} finally {
if (recover) {
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setButtonsVisible(true);
return;
}
}
}
}// End of switch statement
}
private void setServerGameModel() throws IOException {
ClientOptionsJPanel cop = (ClientOptionsJPanel) wizardPages[2];
if (isNewGame()) {
SelectMapJPanel msp2 = (SelectMapJPanel) wizardPages[1];
server.newGame(msp2.getNewMapName());
cop.limitPlayerNames(null);
} else {
// Do nothing since the server is already set up.
}
}
private boolean isNewGame() {
SelectMapJPanel msp2 = (SelectMapJPanel) wizardPages[1];
return msp2.getSelection().equals(SelectMapJPanel.Selection.NEW_GAME);
}
/** Starts the client and server in the same thread. */
private static void startThread(final FreerailsGameServer server,
final GUIClient client) {
try {
Runnable run = new Runnable() {
public void run() {
while (null == client.getWorld()) {
client.update();
server.update();
}
GameModel[] models = new GameModel[] { client, server };
ScreenHandler screenHandler = client.getScreenHandler();
GameLoop gameLoop = new GameLoop(screenHandler, models);
//screenHandler.apply();
gameLoop.run();
}
};
Thread t = new Thread(run, "Client + server main loop");
t.start();
} catch (Exception e) {
exit(e);
}
}
/** Starts the client in a new thread. */
private void startThread(final GUIClient guiClient) {
try {
Runnable run = new Runnable() {
public void run() {
while (null == guiClient.getWorld()) {
guiClient.update();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// do nothing
}
}
GameModel[] models = new GameModel[] { guiClient };
ScreenHandler screenHandler = guiClient.getScreenHandler();
GameLoop gameLoop = new GameLoop(screenHandler, models);
gameLoop.run();
}
};
Thread t = new Thread(run, "Client main loop");
t.start();
} catch (Exception e) {
exit(e);
}
}
/** Starts the server in a new thread. */
private static void startThread(final FreerailsGameServer server) {
try {
Runnable r = new Runnable() {
public void run() {
while (true) {
long startTime = System.currentTimeMillis();
server.update();
long deltatime = System.currentTimeMillis() - startTime;
if (deltatime < 20) {
try {
Thread.sleep(20 - deltatime);
} catch (InterruptedException e) {
// do nothing.
}
}
}
}
};
Thread t = new Thread(r, "FreerailsGameServer");
t.start();
} catch (Exception e) {
exit(e);
}
}
private void initServer() {
SavedGamesManager gamesManager = new SavedGamesManagerImpl();
server = new FreerailsGameServer(gamesManager);
ServerGameModelImpl serverGameModel = new ServerGameModelImpl();
server.setServerGameModel(serverGameModel);
/*
* Set the server field on the connected players panel so that it can
* keep track of who is connected.
*/
ConnectedPlayersJPanel cp = (ConnectedPlayersJPanel) wizardPages[3];
cp.server = server;
server.addPropertyChangeListener(cp);
cp.updateListOfPlayers();
}
/**
* Runs the game.
*/
public static void main(String args[]) {
//SynchronizedEventQueue.use();
// Let the user know if we are using a custom logging config.
String loggingProperties = System
.getProperty("java.util.logging.config.file");
if (null != loggingProperties) {
logger.info("Logging properties file: " + loggingProperties);
}
logger.fine("Started launcher.");
boolean quickstart = false;
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (QUICKSTART.equals(args[i]))
quickstart = true;
}
}
Launcher launcher = new Launcher(quickstart);
launcher.start(quickstart);
}
/**
* Shows GUI. If <code>quickstart</code> is <code>true</code> runs the
* game.
*
* @param quickstart
* boolean
*/
public void start(boolean quickstart) {
setVisible(true);
if (quickstart) {
startGame();
}
}
/** Starts a thread listening for new connections. */
private void prepare2HostNetworkGame(int port) throws IOException {
loadProps();
if (isNewGame()) {
initServer();
}
InetConnectionAccepter accepter = new InetConnectionAccepter(port,
server);
/*
* Note, the thread's name gets set in the run method so there is no
* point setting it here.
*/
Thread t = new Thread(accepter);
t.start();
CardLayout cl = (CardLayout) jPanel1.getLayout();
cl.show(jPanel1, "3");
currentPage = 3;
}
public Launcher(boolean quickstart) {
loadProps();
initComponents();
wizardPages[0] = new LauncherPanel1(this);
wizardPages[1] = new SelectMapJPanel(this);
wizardPages[2] = new ClientOptionsJPanel(this);
wizardPages[3] = new ConnectedPlayersJPanel();
if (!quickstart) {
jPanel1.add(wizardPages[0], "0");
jPanel1.add(wizardPages[1], "1");
jPanel1.add(wizardPages[2], "2");
jPanel1.add(wizardPages[3], "3");
jPanel1.add(progressPanel, "4");
pack();
} else {
prevButton.setVisible(false);
nextButton.setVisible(false);
pack();
}
hideAllMessages();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
nextButton = new javax.swing.JButton();
prevButton = new javax.swing.JButton();
infoLabel = new javax.swing.JLabel();
getContentPane().setLayout(new java.awt.GridBagLayout());
setTitle("Freerails Launcher");
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
jPanel1.setLayout(new java.awt.CardLayout());
jPanel1.setPreferredSize(new java.awt.Dimension(400, 300));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(jPanel1, gridBagConstraints);
nextButton.setText("Next...");
nextButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(nextButton, gridBagConstraints);
prevButton.setText("Back...");
prevButton.setEnabled(false);
prevButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
prevButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(prevButton, gridBagConstraints);
infoLabel.setText("Error messages go here!");
infoLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
infoLabel.setMinimumSize(new java.awt.Dimension(20, 20));
infoLabel.setPreferredSize(new java.awt.Dimension(20, 20));
infoLabel.setVerifyInputWhenFocusTarget(false);
infoLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(infoLabel, gridBagConstraints);
pack();
}// GEN-END:initComponents
private void prevButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_prevButtonActionPerformed
CardLayout cl = (CardLayout) jPanel1.getLayout();
nextIsStart = false;
hideAllMessages();
switch (currentPage) {
case 1:
cl.previous(jPanel1);
currentPage--;
prevButton.setEnabled(false);
break;
case 2:
LauncherPanel1 panel = (LauncherPanel1) wizardPages[0];
if (panel.getMode() == LauncherPanel1.MODE_JOIN_NETWORK_GAME) {
currentPage = 0;
cl.show(jPanel1, "0");
prevButton.setEnabled(false);
} else {
currentPage--;
cl.previous(jPanel1);
}
}
}// GEN-LAST:event_prevButtonActionPerformed
private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_nextButtonActionPerformed
try {
CardLayout cl = (CardLayout) jPanel1.getLayout();
LauncherPanel1 panel = (LauncherPanel1) wizardPages[0];
SelectMapJPanel msp = (SelectMapJPanel) wizardPages[1];
ClientOptionsJPanel cop = (ClientOptionsJPanel) wizardPages[2];
hideAllMessages();
switch (currentPage) {
case 0:
msp.validateInput();
/* Initial game selection page */
switch (panel.getMode()) {
case LauncherPanel1.MODE_SERVER_ONLY:
/* go to map selection screen */
cl.next(jPanel1);
msp.setServerPortPanelVisible(true);
currentPage++;
break;
case LauncherPanel1.MODE_SINGLE_PLAYER:
/* go to map selection screen */
cl.next(jPanel1);
msp.setServerPortPanelVisible(false);
cop.setRemoteServerPanelVisible(false);
currentPage++;
break;
case LauncherPanel1.MODE_START_NETWORK_GAME:
/* go to map selection screen */
msp.setServerPortPanelVisible(true);
cop.setRemoteServerPanelVisible(false);
cl.next(jPanel1);
currentPage++;
break;
case LauncherPanel1.MODE_JOIN_NETWORK_GAME:
/* client display options */
nextIsStart = true;
cl.show(jPanel1, "2");
currentPage = 2;
msp.setServerPortPanelVisible(false);
cop.setRemoteServerPanelVisible(true);
cop.limitPlayerNames(null);
break;
}
prevButton.setEnabled(true);
break;
case 1:
/* map selection page */
if (panel.getMode() == LauncherPanel1.MODE_SERVER_ONLY) {
if (msp.validateInput()) {
prevButton.setEnabled(false);
try {
if (!isNewGame()) {
initServer();
server
.loadgame(ServerControlInterface.FREERAILS_SAV);
}
prepare2HostNetworkGame(msp.getServerPort());
} catch (BindException be) {
// When the port is already in use.
prevButton.setEnabled(true);
setInfoText(be.getMessage(),
LauncherInterface.WARNING);
}
}
} else {
if (isNewGame()) {
cop.limitPlayerNames(null);
} else {
initServer();
server.loadgame(msp.getSaveGameName());
String[] playernames = server.getPlayerNames();
cop.limitPlayerNames(playernames);
}
nextIsStart = true;
prevButton.setEnabled(true);
setNextEnabled(true);
currentPage++;
cl.next(jPanel1);
}
break;
case 2:
/* display mode selection */
if (panel.getMode() == LauncherPanel1.MODE_START_NETWORK_GAME) {
if (msp.validateInput()) {
prevButton.setEnabled(false);
int mode = cop.getScreenMode();
prepare2HostNetworkGame(msp.getServerPort());
client = new GUIClient(cop.getPlayerName(),
progressPanel, mode, cop.getDisplayMode());
client.connect(server, cop.getPlayerName(), "password");
}
} else {
prevButton.setEnabled(false);
cop.setControlsEnabled(false);
startGame();
}
break;
case 3:
try {
/* Connection status screen */
prevButton.setEnabled(false);
setServerGameModel();// TODO catch exception
if (panel.getMode() == LauncherPanel1.MODE_START_NETWORK_GAME) {
startThread(server, client);
cl.show(jPanel1, "4");
} else {
/* Start a stand alone server. */
startThread(server);
setVisible(false);
}
setButtonsVisible(false);
setNextEnabled(false);
} catch (IOException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setNextEnabled(true);
currentPage = 1;
cl.show(jPanel1, "1");
return;
}
break;
default:
throw new IllegalArgumentException(String.valueOf(currentPage));
}
} catch (Exception e) {
exit(e);
}
}// GEN-LAST:event_nextButtonActionPerformed
private static void exit(Exception e) {
ReportBugTextGenerator.unexpectedException(e);
}
/** Exit the Application. */
private void exitForm(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_exitForm
System.exit(0);
}// GEN-LAST:event_exitForm
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JLabel infoLabel;
javax.swing.JPanel jPanel1;
javax.swing.JButton nextButton;
javax.swing.JButton prevButton;
// End of variables declaration//GEN-END:variables
public void setInfoText(String text, int status) {
infoLabel.setText(text);
switch (status) {
case LauncherInterface.ERROR:
infoLabel.setIcon(errorIcon);
nextButton.setEnabled(false);
break;
case LauncherInterface.INFO:
infoLabel.setIcon(infoIcon);
nextButton.setEnabled(true);
break;
case LauncherInterface.WARNING:
infoLabel.setIcon(warningIcon);
nextButton.setEnabled(true);
break;
default:
throw new IllegalArgumentException(String.valueOf(status));
}
}
public void hideAllMessages() {
infoLabel.setText(null);
infoLabel.setIcon(null);
nextButton.setEnabled(true);
}
public void setButtonsVisible(boolean b){
nextButton.setVisible(b);
prevButton.setVisible(b);
}
public void hideErrorMessages() {
if (infoLabel.getIcon() == errorIcon) {
infoLabel.setText(null);
infoLabel.setIcon(null);
nextButton.setEnabled(true);
}
}
private void loadProps(){
try{
props = new Properties();
FileInputStream in = new FileInputStream("freerails.properties");
props.load(in);
in.close();
if(!props.containsKey("freerails.server.port") ||
!props.containsKey("freerails.server.port") ||
!props.containsKey("freerails.server.port")){
throw new Exception();
}
}catch (Exception e){
props = new Properties();
props.setProperty("freerails.server.port", "55000");
props.setProperty("freerails.player.name", System.getProperty("user.name"));
props.setProperty("freerails.server.ip.address", "127.0.0.1");
}
}
public void saveProps(){
try{
FileOutputStream out = new FileOutputStream("freerails.properties");
props.store(out, "---No Comment---");
out.close();
//Copy key-value pairs to System.Properties so
//that they are visible in the game via the
//show java properties menu item.
System.getProperties().putAll(props);
}catch (Exception e){
logger.warning(e.getMessage());
}
}
public void setProperty(String key, String value){
props.setProperty(key, value);
}
public String getProperty(String key){
return props.getProperty(key);
}
}
Methods:
MethodJavadoc
exit
exitForm/** Exit the Application. */
getProperty
hideAllMessages
hideErrorMessages
initComponents/**
initServer
isNewGame
loadProps
main/**
nextButtonActionPerformed
prepare2HostNetworkGame/** Starts a thread listening for new connections. */
prevButtonActionPerformed
saveProps
setButtonsVisible
setInfoText
setNextEnabled
setProperty
setServerGameModel
start/**
startGame
startThread/** Starts the server in a new thread. */
startThread/** Starts the client in a new thread. */
startThread/** Starts the client and server in the same thread. */
jfreerails.launcher.LauncherInterface
Javadoc:
/** * Exposes the methods on the Launcher that the launcher panels may call. * * @author Luke * */
Source code:
/**
* Exposes the methods on the Launcher that the launcher panels may call.
*
* @author Luke
*
*/
public interface LauncherInterface {
public static final int INFO = 0;
public static final int WARNING = 1;
public static final int ERROR = 2;
void setInfoText(String text, int status);
void setNextEnabled(boolean enabled);
void hideErrorMessages();
void hideAllMessages();
void setProperty(String key, String value);
String getProperty(String key);
void saveProps();
}
Methods:
MethodJavadoc
getProperty
hideAllMessages
hideErrorMessages
saveProps
setInfoText
setNextEnabled
setProperty
jfreerails.launcher.LauncherPanel
Javadoc:
/** * @author Luke * */
Source code:
/**
* @author Luke
*
*/
public interface LauncherPanel {
boolean validateInput();
}
Methods:
MethodJavadoc
validateInput
jfreerails.launcher.LauncherPanel1
Javadoc:
/** * The first launcher panel, lets you choose 'single player', 'start network * game' etc. * * @author rtuck99@users.sourceforge.net */
Source code:
/**
* The first launcher panel, lets you choose 'single player', 'start network
* game' etc.
*
* @author rtuck99@users.sourceforge.net
*/
final class LauncherPanel1 extends javax.swing.JPanel {
private static final long serialVersionUID = 3257850965422913590L;
static final int MODE_SINGLE_PLAYER = 0;
static final int MODE_START_NETWORK_GAME = 1;
static final int MODE_JOIN_NETWORK_GAME = 2;
static final int MODE_SERVER_ONLY = 3;
private final ButtonModel[] buttonModels = new ButtonModel[4];
int getMode() {
for (int i = 0; i < buttonModels.length; i++) {
if (buttonGroup1.getSelection() == buttonModels[i]) {
return i;
}
}
assert false;
return 0;
}
/*
* private void validateSettings() { boolean isValid = false; String
* infoText = null;
*
* switch (getMode()) {
*
* case MODE_SINGLE_PLAYER: isValid = true; break; case
* MODE_START_NETWORK_GAME: case MODE_SERVER_ONLY: isValid = true; break;
* case MODE_JOIN_NETWORK_GAME: isValid = true; break; }
* owner.setInfoText(infoText, LauncherInterface.WARNING);
* owner.setNextEnabled(isValid); }
*/
public LauncherPanel1(LauncherInterface owner) {
initComponents();
buttonModels[MODE_SINGLE_PLAYER] = singlePlayerButton.getModel();
buttonModels[MODE_START_NETWORK_GAME] = startNetworkButton.getModel();
buttonModels[MODE_JOIN_NETWORK_GAME] = joinNetworkButton.getModel();
buttonModels[MODE_SERVER_ONLY] = serverOnlyButton.getModel();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup1 = new javax.swing.ButtonGroup();
singlePlayerButton = new javax.swing.JRadioButton();
startNetworkButton = new javax.swing.JRadioButton();
joinNetworkButton = new javax.swing.JRadioButton();
serverOnlyButton = new javax.swing.JRadioButton();
paddingJPanel = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
setBorder(new javax.swing.border.TitledBorder(
new javax.swing.border.EtchedBorder(), "Select Game Type"));
buttonGroup1.add(singlePlayerButton);
singlePlayerButton.setSelected(true);
singlePlayerButton.setText("Single-Player");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(singlePlayerButton, gridBagConstraints);
buttonGroup1.add(startNetworkButton);
startNetworkButton.setText("Start a network game");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(startNetworkButton, gridBagConstraints);
buttonGroup1.add(joinNetworkButton);
joinNetworkButton.setText("Join a network game");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(joinNetworkButton, gridBagConstraints);
buttonGroup1.add(serverOnlyButton);
serverOnlyButton.setText("Server only");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(serverOnlyButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(paddingJPanel, gridBagConstraints);
}// GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.ButtonGroup buttonGroup1;
javax.swing.JRadioButton joinNetworkButton;
javax.swing.JPanel paddingJPanel;
javax.swing.JRadioButton serverOnlyButton;
javax.swing.JRadioButton singlePlayerButton;
javax.swing.JRadioButton startNetworkButton;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
getMode
initComponents/**
jfreerails.launcher.ProgressJPanel
Javadoc:
/** * A JPanel that displays a splash screen and a progress bar. * * @author Luke */
Source code:
/**
* A JPanel that displays a splash screen and a progress bar.
*
* @author Luke
*/
public class ProgressJPanel extends javax.swing.JPanel implements
FreerailsProgressMonitor{
private static final long serialVersionUID = 3256445798203273776L;
int step, stepSize;
final int numSteps = 5;
LauncherInterface owner;
public void setValue(int i) {
int value = i * 100 / stepSize;
value += 100 * step;
progressBar.setValue(value);
}
public void nextStep(int max) {
//So that the waiting for game to start message
//goes away.
owner.hideAllMessages();
step++;
stepSize = max;
if(numSteps < step)
throw new IllegalStateException();
}
public void finished() {
if(numSteps-1 != step)
throw new IllegalStateException(numSteps +"!="+ step);
getTopLevelAncestor().setVisible(false);
}
/** Creates new form ProgressJPanel */
public ProgressJPanel(LauncherInterface owner) {
this.owner = owner;
initComponents();
progressBar.setMaximum(numSteps * 100);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
progressBar = new javax.swing.JProgressBar();
splashImage = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(3, 7, 3, 7);
add(progressBar, gridBagConstraints);
splashImage.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
splashImage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jfreerails/client/graphics/splash_screen.jpg")));
add(splashImage, new java.awt.GridBagConstraints());
}
// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JProgressBar progressBar;
javax.swing.JLabel splashImage;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
finished
initComponents/** This method is called from within the constructor to
nextStep
setValue
jfreerails.launcher.SelectMapJPanel
Javadoc:
/** * The Launcher panel that lets you load a game or start a new game with a * choice of maps. * @author Luke */
Source code:
/**
* The Launcher panel that lets you load a game or start a new game with a
* choice of maps.
* @author Luke
*/
public class SelectMapJPanel extends javax.swing.JPanel implements LauncherPanel {
private static final long serialVersionUID = 3763096353857024568L;
private static final String SELECT_A_MAP = "Select a map.";
private static final String INVALID_PORT = "A valid port value is between between 0 and 65535.";
private final LauncherInterface owner;
public enum Selection {NONE, NEW_GAME, LOAD_GAME};
Selection getSelection() {
if( newmapsJList.getSelectedIndex() != -1 ){
savedmapsJList.setSelectedIndex(-1);
return Selection.NEW_GAME;
}
if(savedmapsJList.getSelectedIndex() != -1){
return Selection.LOAD_GAME;
}
return Selection.NONE;
}
void setServerPortPanelVisible(boolean b) {
this.jPanel3.setVisible(b);
}
public String getNewMapName() {
return (String) newmapsJList.getSelectedValue();
}
public String getSaveGameName() {
return (String) savedmapsJList.getSelectedValue();
}
SelectMapJPanel(LauncherInterface owner) {
this.owner = owner;
initComponents();
/* initialise the map list */
SavedGamesManagerImpl sgm = new SavedGamesManagerImpl();
newmapsJList.setListData(sgm.getNewMapNames());
newmapsJList.setSelectedIndex(0);
savedmapsJList.setListData(sgm.getSaveGameNames());
owner.setNextEnabled(true);
// Listen for changes in the server port text box.
serverPort.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
validateInput();
}
public void removeUpdate(DocumentEvent e) {
validateInput();
}
public void changedUpdate(DocumentEvent e) {
validateInput();
}
});
}
int getServerPort() {
String s = serverPort.getText();
return Integer.parseInt(s);
}
public boolean validateInput() {
/* Validate map selection. */
if (this.getSelection().equals(Selection.NONE)) {
owner.setInfoText(SELECT_A_MAP, LauncherInterface.ERROR);
return false;
}
/* Validate port. */
try {
int port = getServerPort();
if (port < 0 || port > 65535) {
owner.setInfoText(INVALID_PORT, LauncherInterface.ERROR);
return false;
}
} catch (Exception e) {
owner.setInfoText(INVALID_PORT, LauncherInterface.ERROR);
return false;
}
/* Everything is ok. */
owner.hideErrorMessages();
owner.setProperty("freerails.server.port", this.serverPort.getText());
owner.saveProps();
return true;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
newmapsJList = new javax.swing.JList();
jPanel4 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
savedmapsJList = new javax.swing.JList();
jPanel3 = new javax.swing.JPanel();
portLabel = new javax.swing.JLabel();
serverPort = new javax.swing.JTextField();
jPanel2 = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel1.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), "New Game"));
jPanel1.setPreferredSize(null);
jScrollPane1.setViewportBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
newmapsJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
newmapsJList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
newmapsJListValueChanged(evt);
}
});
jScrollPane1.setViewportView(newmapsJList);
jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jPanel1, gridBagConstraints);
jPanel4.setLayout(new java.awt.BorderLayout());
jPanel4.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), "Load game"));
jPanel4.setPreferredSize(null);
jPanel4.setRequestFocusEnabled(false);
jScrollPane2.setViewportBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
savedmapsJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
savedmapsJList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
savedmapsJListValueChanged(evt);
}
});
jScrollPane2.setViewportView(savedmapsJList);
jPanel4.add(jScrollPane2, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jPanel4, gridBagConstraints);
jPanel3.setLayout(new java.awt.GridBagLayout());
jPanel3.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), "Server port"));
portLabel.setText("Port:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel3.add(portLabel, gridBagConstraints);
serverPort.setColumns(6);
serverPort.setText( owner.getProperty("freerails.server.port"));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel3.add(serverPort, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
jPanel3.add(jPanel2, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
add(jPanel3, gridBagConstraints);
}
// </editor-fold>//GEN-END:initComponents
private void savedmapsJListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_savedmapsJListValueChanged
if(savedmapsJList.getSelectedIndex() != -1)
newmapsJList.clearSelection();
validateInput();
}//GEN-LAST:event_savedmapsJListValueChanged
private void newmapsJListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_newmapsJListValueChanged
if(newmapsJList.getSelectedIndex() != -1)
savedmapsJList.clearSelection();
validateInput();
}//GEN-LAST:event_newmapsJListValueChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JPanel jPanel1;
javax.swing.JPanel jPanel2;
javax.swing.JPanel jPanel3;
javax.swing.JPanel jPanel4;
javax.swing.JScrollPane jScrollPane1;
javax.swing.JScrollPane jScrollPane2;
javax.swing.JList newmapsJList;
javax.swing.JLabel portLabel;
javax.swing.JList savedmapsJList;
javax.swing.JTextField serverPort;
// End of variables declaration//GEN-END:variables
}
Methods:
MethodJavadoc
getNewMapName
getSaveGameName
getSelection
getServerPort
initComponents/** This method is called from within the constructor to
newmapsJListValueChanged
savedmapsJListValueChanged
setServerPortPanelVisible/**
validateInput
jfreerails.move.AbstractMoveTestCase
Javadoc:
/** * All TestCases for moves should extend this class. * * @author Luke * */
Source code:
/**
* All TestCases for moves should extend this class.
*
* @author Luke
*
*/
public abstract class AbstractMoveTestCase extends TestCase {
private boolean hasSetupBeenCalled = false;
protected World world;
protected AbstractMoveTestCase() {
}
public AbstractMoveTestCase(String str) {
super(str);
}
protected void assertDoMoveFails(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.doMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertTrue("Move went through when it should have failed", !ms.ok);
}
protected void assertDoMoveIsOk(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.doMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals(MoveStatus.MOVE_OK, ms);
}
protected void assertDoThenUndoLeavesWorldUnchanged(Move m) {
try {
World w = getWorld();
World before = (World) Utils.cloneBySerialisation(w);
assertEquals(before, w);
assertTrue(m.doMove(w, Player.AUTHORITATIVE).ok);
World after = (World) Utils.cloneBySerialisation(w);
assertFalse(after.equals(before));
boolean b = m.undoMove(w, Player.AUTHORITATIVE).ok;
assertTrue(b);
assertEquals(before, w);
} catch (Exception e) {
e.printStackTrace();
assertTrue(false);
}
}
/**
* This method asserts that if we serialise then deserialize the specified
* move, the specified move is equal to the deserialized move. The assertion
* depends on the move being serializable and the equals method being
* implemented correctly. Also checks that the hashcode does not change.
*
* @param m
*/
protected void assertSurvivesSerialisation(FreerailsSerializable m) {
assertEquals("Reflexivity violated: the move does not equal itself", m,
m);
try {
Object o = Utils.cloneBySerialisation(m);
assertEquals(m, o);
assertEquals("The hashcodes should be the same!", m.hashCode(), o
.hashCode());
} catch (Exception e) {
e.printStackTrace();
assertTrue(false);
}
}
protected void assertOkAndRepeatable(Move m) {
assertSetupHasBeenCalled();
// Do move
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
// Since it leaves the world unchanged it should also be
// possible to undo it repeatably
assertTryUndoMoveIsOk(m);
assertUndoMoveIsOk(m);
assertTryUndoMoveIsOk(m);
assertUndoMoveIsOk(m);
}
/**
* Generally moves should not be repeatable. For example, if we have just
* removed a piece of track, that piece of track is gone, so we cannot
* remove it again.
*/
protected void assertOkButNotRepeatable(Move m) {
assertSetupHasBeenCalled();
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
assertTryMoveFails(m);
assertDoMoveFails(m);
assertTryUndoMoveIsOk(m);
assertUndoMoveIsOk(m);
assertTryUndoMoveFails(m);
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
}
private void assertSetupHasBeenCalled() {
assertTrue("AbstractMoveTestCase.setUp has not been called!",
hasSetupBeenCalled());
}
protected void assertTryMoveFails(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertTrue("Move went through when it should have failed", !ms.ok);
}
protected void assertTryMoveIsOk(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals("First try failed", MoveStatus.MOVE_OK, ms);
ms = m.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals(
"Second try failed, this suggests that the tryDoMove method failed to leave the world unchanged!",
MoveStatus.MOVE_OK, ms);
}
protected void assertTryUndoMoveFails(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryUndoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertTrue("Move went through when it should have failed", !ms.ok);
}
protected void assertTryUndoMoveIsOk(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryUndoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals("First try failed", MoveStatus.MOVE_OK, ms);
ms = m.tryUndoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals(
"Second try failed, this suggests that the tryDoMove method failed to leave the world unchanged!",
MoveStatus.MOVE_OK, ms);
}
protected void assertUndoMoveFails(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryUndoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertTrue("Move went through when it should have failed", !ms.ok);
}
protected void assertUndoMoveIsOk(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.undoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals(MoveStatus.MOVE_OK, ms);
}
FreerailsPrincipal getPrincipal() {
return world.getPlayer(0).getPrincipal();
}
World getWorld() {
return world;
}
protected boolean hasSetupBeenCalled() {
return hasSetupBeenCalled;
}
protected void setHasSetupBeenCalled(boolean hasSetupBeenCalled) {
this.hasSetupBeenCalled = hasSetupBeenCalled;
}
@Override
protected void setUp() throws Exception {
setHasSetupBeenCalled(true);
setupWorld();
}
protected void setupWorld() {
setWorld(new WorldImpl(10, 10));
// Set the time..
getWorld().set(ITEM.CALENDAR, new GameCalendar(12000, 1840));
getWorld().addPlayer(MapFixtureFactory.TEST_PLAYER);
}
void setWorld(World world) {
this.world = world;
}
public void testMove(){}
protected void assertTrackHere(int x, int y) {
FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
assertTrue(tile.hasTrack());
}
protected void assertTrackHere(PathOnTiles path) {
ImPoint start = path.getStart();
int x = start.x;
int y = start.y;
for (int i = 0; i < path.steps(); i++) {
assertTrackHere(x, y);
Step step = path.getStep(i);
x += step.deltaX;
y += step.deltaY;
assertTrackHere(x, y);
}
}
}
Methods:
MethodJavadoc
assertDoMoveFails
assertDoMoveIsOk
assertDoThenUndoLeavesWorldUnchanged
assertOkAndRepeatable
assertOkButNotRepeatable/**
assertSetupHasBeenCalled
assertSurvivesSerialisation/**
assertTrackHere
assertTrackHere
assertTryMoveFails
assertTryMoveIsOk
assertTryUndoMoveFails
assertTryUndoMoveIsOk
assertUndoMoveFails
assertUndoMoveIsOk
getPrincipal
getWorld
hasSetupBeenCalled
setHasSetupBeenCalled
setUp
setWorld
setupWorld
testMove
jfreerails.move.AddActiveEntityMove
Javadoc:
/** * A move that adds an active entity. An active entity is something whose state * may be continually changing. An example is a train - it is an active entity * since while it is moving its position is continually changing. * * @author Luke * @see NextActivityMove */
Source code:
/**
* A move that adds an active entity. An active entity is something whose state
* may be continually changing. An example is a train - it is an active entity
* since while it is moving its position is continually changing.
*
* @author Luke
* @see NextActivityMove
*/
public class AddActiveEntityMove implements Move {
private static final long serialVersionUID = 8732702087937675013L;
private final Activity activity;
private final FreerailsPrincipal principal;
private final int index;
public AddActiveEntityMove(Activity activity, int index,
FreerailsPrincipal principal) {
this.activity = activity;
this.index = index;
this.principal = principal;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof AddActiveEntityMove))
return false;
final AddActiveEntityMove addActiveEntityMove = (AddActiveEntityMove) o;
if (index != addActiveEntityMove.index)
return false;
if (!activity.equals(addActiveEntityMove.activity))
return false;
if (!principal.equals(addActiveEntityMove.principal))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = activity.hashCode();
result = 29 * result + principal.hashCode();
result = 29 * result + index;
return result;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (index != w.size(principal))
return MoveStatus.moveFailed("index != w.size(listKey, p)");
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int expectedSize = index + 1;
if (expectedSize != w.size(principal))
return MoveStatus
.moveFailed("(index + 1) != w.size(listKey, principal)");
ActivityIterator ai = w.getActivities(principal, index);
if (ai.hasNext())
return MoveStatus
.moveFailed("There should be exactly one activity!");
Activity act = ai.getActivity();
if (!act.equals(activity))
return MoveStatus.moveFailed("Expected " + activity.toString()
+ " but found " + act.toString());
return MoveStatus.MOVE_OK;
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.ok)
w.addActiveEntity(principal, activity);
return ms;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.ok)
w.removeLastActiveEntity(principal);
return ms;
}
}
Methods:
MethodJavadoc
doMove
tryDoMove
tryUndoMove
undoMove
jfreerails.move.AddCargoBundleMove
Javadoc:
/** * This Move adds a cargo bundle to the cargo bundle list. * * @author Luke * */
Source code:
/**
* This Move adds a cargo bundle to the cargo bundle list.
*
* @author Luke
*
*/
public class AddCargoBundleMove extends AddItemToListMove {
private static final long serialVersionUID = 3257288049795674934L;
public AddCargoBundleMove(int i, ImmutableCargoBundle item,
FreerailsPrincipal p) {
super(KEY.CARGO_BUNDLES, i, item, p);
}
}
No methods in this class.
jfreerails.move.AddItemToListMove
Javadoc:
/** * All moves that add an item to a list should extend this class. * * @author Luke * */
Source code:
/**
* All moves that add an item to a list should extend this class.
*
* @author Luke
*
*/
public class AddItemToListMove implements ListMove {
private static final long serialVersionUID = 3256721779916747824L;
private final KEY listKey;
private final int index;
private final FreerailsPrincipal principal;
private final FreerailsSerializable item;
public int getIndex() {
return index;
}
@Override
public int hashCode() {
int result;
result = listKey.hashCode();
result = 29 * result + index;
result = 29 * result + principal.hashCode();
result = 29 * result + (item != null ? item.hashCode() : 0);
return result;
}
public KEY getKey() {
return listKey;
}
public AddItemToListMove(KEY key, int i, FreerailsSerializable item,
FreerailsPrincipal p) {
this.listKey = key;
this.index = i;
this.item = item;
this.principal = p;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.size(this.principal, listKey) != index) {
return MoveStatus.moveFailed("Expected size of "
+ listKey.toString() + " list is " + index
+ " but actual size is " + w.size(this.principal, listKey));
}
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int expectListSize = index + 1;
if (w.size(this.principal, listKey) != expectListSize) {
return MoveStatus.moveFailed("Expected size of "
+ listKey.toString() + " list is " + expectListSize
+ " but actual size is " + w.size(this.principal, listKey));
}
return MoveStatus.MOVE_OK;
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.isOk()) {
w.add(this.principal, listKey, this.item);
}
return ms;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.isOk()) {
w.removeLast(this.principal, listKey);
}
return ms;
}
@Override
public boolean equals(Object o) {
if (o instanceof AddItemToListMove) {
AddItemToListMove test = (AddItemToListMove) o;
if (null == this.item) {
if (null != test.item) {
return false;
}
} else if (!this.item.equals(test.getAfter())) {
return false;
}
if (this.index != test.index) {
return false;
}
if (this.listKey != test.listKey) {
return false;
}
return true;
}
return false;
}
public FreerailsSerializable getBefore() {
return null;
}
public FreerailsSerializable getAfter() {
return item;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer(this.getClass().getName());
sb.append("\n list=");
sb.append(listKey.toString());
sb.append("\n index =");
sb.append(index);
sb.append("\n item =");
sb.append(item);
return sb.toString();
}
public FreerailsPrincipal getPrincipal() {
return principal;
}
}
Methods:
MethodJavadoc
doMove
getAfter
getBefore
getIndex
getKey
getPrincipal
tryDoMove
tryUndoMove
undoMove
jfreerails.move.AddItemToSharedListMove
Javadoc:
/** * All moves that add an item to a shared list should extend this class. * * @author Luke * */
Source code:
/**
* All moves that add an item to a shared list should extend this class.
*
* @author Luke
*
*/
public class AddItemToSharedListMove implements Move {
private static final long serialVersionUID = 3762256352759722807L;
private final SKEY listKey;
private final int index;
private final FreerailsSerializable item;
public int getIndex() {
return index;
}
@Override
public int hashCode() {
int result;
result = listKey.hashCode();
result = 29 * result + index;
result = 29 * result + (item != null ? item.hashCode() : 0);
return result;
}
public SKEY getKey() {
return listKey;
}
protected AddItemToSharedListMove(SKEY key, int i,
FreerailsSerializable item) {
this.listKey = key;
this.index = i;
this.item = item;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.size(listKey) != index) {
return MoveStatus.moveFailed("Expected size of "
+ listKey.toString() + " list is " + index
+ " but actual size is " + w.size(listKey));
}
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int expectListSize = index + 1;
if (w.size(listKey) != expectListSize) {
return MoveStatus.moveFailed("Expected size of "
+ listKey.toString() + " list is " + expectListSize
+ " but actual size is " + w.size(listKey));
}
return MoveStatus.MOVE_OK;
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.isOk()) {
w.add(listKey, this.item);
}
return ms;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.isOk()) {
w.removeLast(listKey);
}
return ms;
}
@Override
public boolean equals(Object o) {
if (o instanceof AddItemToSharedListMove) {
AddItemToSharedListMove test = (AddItemToSharedListMove) o;
if (!this.item.equals(test.getAfter())) {
return false;
}
if (this.index != test.index) {
return false;
}
if (this.listKey != test.listKey) {
return false;
}
return true;
}
return false;
}
public FreerailsSerializable getBefore() {
return null;
}
public FreerailsSerializable getAfter() {
return item;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer(this.getClass().getName());
sb.append("\nlist=");
sb.append(listKey.toString());
sb.append("\n index =");
sb.append(this.index);
sb.append("\n item =");
sb.append(this.item.toString());
return sb.toString();
}
}
Methods:
MethodJavadoc
doMove
getAfter
getBefore
getIndex
getKey
tryDoMove
tryUndoMove
undoMove
jfreerails.move.AddPlayerMove
Javadoc:
/** * Adds a player to the world. * * @author Luke */
Source code:
/**
* Adds a player to the world.
*
* @author Luke
*/
public class AddPlayerMove implements Move, ServerMove {
private static final long serialVersionUID = 3977580277537322804L;
private final Player player2add;
private AddPlayerMove(Player p) {
player2add = p;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof AddPlayerMove))
return false;
final AddPlayerMove addPlayerMove = (AddPlayerMove) o;
if (!player2add.equals(addPlayerMove.player2add))
return false;
return true;
}
@Override
public int hashCode() {
return player2add.hashCode();
}
public static AddPlayerMove generateMove(ReadOnlyWorld w, Player player) {
/**
* create a new player with a corresponding Principal
*/
Player player2add = new Player(player.getName(), w.getNumberOfPlayers());
return new AddPlayerMove(player2add);
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (isAlreadyASimilarPlayer(w))
return MoveStatus
.moveFailed("There is already a player with the same name.");
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int numPlayers = w.getNumberOfPlayers();
Player pp = w.getPlayer(numPlayers - 1);
if (pp.equals(player2add)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("The last player is " + pp.getName()
+ "not " + player2add.getName());
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (!ms.ok)
return ms;
int playerId = w.addPlayer(this.player2add);
// Sell the player 2 $500,000 bonds at 5% interest.
FreerailsPrincipal principal = player2add.getPrincipal();
w.addTransaction(principal, BondTransaction.issueBond(5));
//Issue stock
Money initialStockPrice = new Money(5);
Transaction t = StockTransaction.issueStock(playerId, 100000,
initialStockPrice);
w.addTransaction(principal, t);
return ms;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (!ms.ok)
return ms;
w.removeLastTransaction(player2add.getPrincipal());
w.removeLastTransaction(player2add.getPrincipal());
w.removeLastPlayer();
return ms;
}
private boolean isAlreadyASimilarPlayer(World w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
Player pp = w.getPlayer(i);
if (pp.getName().equalsIgnoreCase(this.player2add.getName())) {
return true;
}
}
return false;
}
}
Methods:
MethodJavadoc
doMove
generateMove
isAlreadyASimilarPlayer
tryDoMove
tryUndoMove
undoMove
jfreerails.move.AddStationMove
Javadoc:
/** * This {@link CompositeMove}adds a station to the station list and adds a * cargo bundle (to store the cargo waiting at the station) to the cargo bundle * list. * * @author Luke * */
Source code:
/**
* This {@link CompositeMove}adds a station to the station list and adds a
* cargo bundle (to store the cargo waiting at the station) to the cargo bundle
* list.
*
* @author Luke
*
*/
public class AddStationMove extends CompositeMove {
private static final long serialVersionUID = 3256728398461089080L;
private AddStationMove(Move[] moves) {
super(moves);
}
public StationModel getNewStation() {
AddItemToListMove addStation = (AddItemToListMove) super.getMove(2);
return (StationModel) addStation.getAfter();
}
public static AddStationMove generateMove(ReadOnlyWorld w,
String stationName, ImPoint p,
ChangeTrackPieceMove upgradeTrackMove, FreerailsPrincipal principal) {
int cargoBundleNumber = w.size(principal, KEY.CARGO_BUNDLES);
Move addCargoBundleMove = new AddCargoBundleMove(cargoBundleNumber,
ImmutableCargoBundle.EMPTY_BUNDLE, principal);
int stationNumber = w.size(principal, KEY.STATIONS);
StationModel station = new StationModel(p.x, p.y, stationName, w
.size(SKEY.CARGO_TYPES), cargoBundleNumber);
Move addStation = new AddItemToListMove(KEY.STATIONS, stationNumber,
station, principal);
return new AddStationMove(new Move[] { upgradeTrackMove,
addCargoBundleMove, addStation });
}
public static AddStationMove upgradeStation(
ChangeTrackPieceMove upgradeTrackMove) {
return new AddStationMove(new Move[] { upgradeTrackMove });
}
}
Methods:
MethodJavadoc
generateMove
getNewStation
upgradeStation
jfreerails.move.AddTransactionMove
Javadoc:
/** * This {@link Move} adds a {@link Transaction} to a players bank account on the * {@link World} object. * * @author Luke Lindsay * */
Source code:
/**
* This {@link Move} adds a {@link Transaction} to a players bank account on the
* {@link World} object.
*
* @author Luke Lindsay
*
*/
public class AddTransactionMove implements Move {
private static final long serialVersionUID = 3976738055925019701L;
private final Transaction transaction;
private final FreerailsPrincipal principal;
/** Whether the move fails if there is not enough cash. */
private final boolean constrained;
public Transaction getTransaction() {
return transaction;
}
@Override
public int hashCode() {
int result;
result = transaction.hashCode();
result = 29 * result + principal.hashCode();
result = 29 * result + (constrained ? 1 : 0);
return result;
}
public AddTransactionMove(FreerailsPrincipal account, Transaction t) {
if (null == t) {
throw new NullPointerException();
}
principal = account;
transaction = t;
constrained = false;
}
public AddTransactionMove(FreerailsPrincipal account, Transaction t,
boolean constrain) {
principal = account;
transaction = t;
constrained = constrain;
if (null == t) {
throw new NullPointerException();
}
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.isPlayer(principal)) {
if (this.constrained) {
long bankBalance = w.getCurrentBalance(principal).getAmount();
long transactionAmount = this.transaction.deltaCash()
.getAmount();
long balanceAfter = bankBalance + transactionAmount;
if (transactionAmount < 0 && balanceAfter < 0) {
return MoveStatus.moveFailed("You can't afford that!");
}
}
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed(p.getName()
+ " does not have a bank account.");
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int size = w.getNumberOfTransactions(this.principal);
if (0 == size) {
return MoveStatus.moveFailed("No transactions to remove!");
}
Transaction lastTransaction = w
.getTransaction(this.principal, size - 1);
if (lastTransaction.equals(this.transaction)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + this.transaction
+ "but found " + lastTransaction);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.ok) {
w.addTransaction(this.principal, this.transaction);
}
return ms;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.ok) {
w.removeLastTransaction(this.principal);
}
return ms;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AddTransactionMove) {
AddTransactionMove test = (AddTransactionMove) obj;
return test.principal.equals(this.principal)
&& test.transaction.equals(this.transaction);
}
return false;
}
public FreerailsPrincipal getPrincipal() {
return principal;
}
}
Methods:
MethodJavadoc
doMove
getPrincipal
getTransaction
tryDoMove
tryUndoMove
undoMove
jfreerails.move.ChangeCargoBundleMove
Javadoc:
/** * This {@link Move} changes a cargo bundle (cargo bundles are used to represent * the cargo carried by trains and the cargo waiting at stations). * * @author Luke * */
Source code:
/**
* This {@link Move} changes a cargo bundle (cargo bundles are used to represent
* the cargo carried by trains and the cargo waiting at stations).
*
* @author Luke
*
*/
public class ChangeCargoBundleMove extends ChangeItemInListMove {
private static final long serialVersionUID = 3258126960072143408L;
public ChangeCargoBundleMove(ImmutableCargoBundle before,
ImmutableCargoBundle after, int bundleNumber, FreerailsPrincipal p) {
super(KEY.CARGO_BUNDLES, bundleNumber, before, after, p);
}
}
No methods in this class.
jfreerails.move.ChangeGameSpeedMove
Javadoc:
/** * * Changes the game speed item on the world object. * * @author Jan Tozicka * */
Source code:
/**
*
* Changes the game speed item on the world object.
*
* @author Jan Tozicka
*
*/
public class ChangeGameSpeedMove implements Move {
private static final long serialVersionUID = 3545794368956086071L;
private final GameSpeed oldSpeed;
private final GameSpeed newSpeed;
public static ChangeGameSpeedMove getMove(ReadOnlyWorld w,
GameSpeed newGameSpeed) {
return new ChangeGameSpeedMove((GameSpeed) w.get(ITEM.GAME_SPEED),
newGameSpeed);
}
private ChangeGameSpeedMove(GameSpeed before, GameSpeed after) {
oldSpeed = before;
newSpeed = after;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.get(ITEM.GAME_SPEED).equals(oldSpeed)) {
return MoveStatus.MOVE_OK;
}
String string = "oldSpeed = " + oldSpeed.getSpeed() + " <=> "
+ "currentSpeed "
+ ((GameSpeed) w.get(ITEM.GAME_SPEED)).getSpeed();
return MoveStatus.moveFailed(string);
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
GameSpeed speed = ((GameSpeed) w.get(ITEM.GAME_SPEED));
if (speed.equals(newSpeed)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + newSpeed + ", found "
+ speed);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryDoMove(w, p);
if (status.ok) {
w.set(ITEM.GAME_SPEED, newSpeed);
}
return status;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryUndoMove(w, p);
if (status.isOk()) {
w.set(ITEM.GAME_SPEED, oldSpeed);
}
return status;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ChangeGameSpeedMove))
return false;
final ChangeGameSpeedMove changeGameSpeedMove = (ChangeGameSpeedMove) o;
if (!newSpeed.equals(changeGameSpeedMove.newSpeed))
return false;
if (!oldSpeed.equals(changeGameSpeedMove.oldSpeed))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = oldSpeed.hashCode();
result = 29 * result + newSpeed.hashCode();
return result;
}
public int getNewSpeed() {
return newSpeed.getSpeed();
}
@Override
public String toString() {
return "ChangeGameSpeedMove: " + oldSpeed + "=>" + newSpeed;
}
}
Methods:
MethodJavadoc
doMove
getMove
getNewSpeed
tryDoMove
tryUndoMove
undoMove
jfreerails.move.ChangeItemInListMove
Javadoc:
/** * All Moves that replace an item in a list with another should extend this * class. * * @author Luke * */
Source code:
/**
* All Moves that replace an item in a list with another should extend this
* class.
*
* @author Luke
*
*/
public class ChangeItemInListMove implements ListMove {
private static final long serialVersionUID = -4457694821370844051L;
private final KEY listKey;
private final int index;
private final FreerailsSerializable before;
private final FreerailsSerializable after;
private final FreerailsPrincipal principal;
public ChangeItemInListMove(KEY k, int index, FreerailsSerializable before,
FreerailsSerializable after, FreerailsPrincipal p) {
this.before = before;
this.after = after;
this.index = index;
this.listKey = k;
this.principal = p;
}
public boolean beforeEqualsAfter(){
return Utils.equal(this.before, this.after);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
return move(after, before, w);
}
@Override
public boolean equals(Object o) {
if (o instanceof ChangeItemInListMove) {
ChangeItemInListMove test = (ChangeItemInListMove) o;
if (!before.equals(test.getBefore())) {
return false;
}
if (!after.equals(test.getAfter())) {
return false;
}
if (index != test.index) {
return false;
}
if (listKey != test.listKey) {
return false;
}
return true;
}
return false;
}
public FreerailsSerializable getAfter() {
return after;
}
public FreerailsSerializable getBefore() {
return before;
}
public int getIndex() {
return index;
}
public KEY getKey() {
return listKey;
}
public FreerailsPrincipal getPrincipal() {
return principal;
}
@Override
public int hashCode() {
int result;
result = listKey.hashCode();
result = 29 * result + index;
result = 29 * result + (before != null ? before.hashCode() : 0);
result = 29 * result + (after != null ? after.hashCode() : 0);
result = 29 * result + principal.hashCode();
return result;
}
protected MoveStatus move(FreerailsSerializable to,
FreerailsSerializable from, World w) {
MoveStatus ms = tryMove(to, from, w);
if (ms.ok) {
w.set(principal, listKey, index, to);
}
return ms;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(getClass().getName());
sb.append(" before: ");
sb.append(before.toString());
sb.append(" after: ");
sb.append(after.toString());
return sb.toString();
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
return tryMove(after, before, w);
}
protected MoveStatus tryMove(FreerailsSerializable to,
FreerailsSerializable from, World w) {
if (index >= w.size(principal, listKey)) {
return MoveStatus.moveFailed("w.size(listKey) is "
+ w.size(principal, listKey) + " but index is " + index);
}
FreerailsSerializable item2change = w.get(principal, listKey, index);
if (null == item2change) {
if (null == from) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected null but found " + from);
}
if (!from.equals(item2change)) {
String message = "Expected " + from.toString() + " but found "
+ to.toString();
return MoveStatus.moveFailed(message);
}
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
return tryMove(before, after, w);
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
return move(before, after, w);
}
}
Methods:
MethodJavadoc
beforeEqualsAfter
doMove
getAfter
getBefore
getIndex
getKey
getPrincipal
move
tryDoMove/**
tryMove
tryUndoMove
undoMove
jfreerails.move.ChangeProductionAtEngineShopMove
Javadoc:
/** * This Move changes what is being built at an engine shop - when a client wants * to build a train, it should send an instance of this class to the server. * * @author Luke * */
Source code:
/**
* This Move changes what is being built at an engine shop - when a client wants
* to build a train, it should send an instance of this class to the server.
*
* @author Luke
*
*/
public class ChangeProductionAtEngineShopMove implements Move {
private static final long serialVersionUID = 3905519384997737520L;
private final ImList<PlannedTrain> before;
private final ImList<PlannedTrain> after;
private final int stationNumber;
private final FreerailsPrincipal principal;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ChangeProductionAtEngineShopMove))
return false;
final ChangeProductionAtEngineShopMove changeProductionAtEngineShopMove = (ChangeProductionAtEngineShopMove) o;
if (stationNumber != changeProductionAtEngineShopMove.stationNumber)
return false;
if (after != null ? !after
.equals(changeProductionAtEngineShopMove.after)
: changeProductionAtEngineShopMove.after != null)
return false;
if (before != null ? !before
.equals(changeProductionAtEngineShopMove.before)
: changeProductionAtEngineShopMove.before != null)
return false;
if (!principal.equals(changeProductionAtEngineShopMove.principal))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = (before != null ? before.hashCode() : 0);
result = 29 * result + (after != null ? after.hashCode() : 0);
result = 29 * result + stationNumber;
result = 29 * result + principal.hashCode();
return result;
}
public ChangeProductionAtEngineShopMove(ImList<PlannedTrain> b,
ImList<PlannedTrain> a, int station, FreerailsPrincipal p) {
this.before = b;
this.after = a;
this.stationNumber = station;
this.principal = p;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
return tryMove(w, before);
}
private MoveStatus tryMove(World w, ImList<PlannedTrain> stateA) {
// Check that the specified station exists.
if (!w.boundsContain(principal, KEY.STATIONS, this.stationNumber)) {
return MoveStatus.moveFailed(this.stationNumber + " " + principal);
}
StationModel station = (StationModel) w.get(principal, KEY.STATIONS,
stationNumber);
if (null == station) {
return MoveStatus.moveFailed(this.stationNumber + " " + principal
+ " is does null");
}
// Check that the station is building what we expect.
if (null == station.getProduction()) {
if (null == stateA) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed(this.stationNumber + " " + principal);
}
if (station.getProduction().equals(stateA)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed(this.stationNumber + " " + principal);
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
return tryMove(w, after);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryDoMove(w, p);
if (status.isOk()) {
StationModel station = (StationModel) w.get(principal,
KEY.STATIONS, stationNumber);
station = new StationModel(station, this.after);
w.set(principal, KEY.STATIONS, stationNumber, station);
}
return status;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryUndoMove(w, p);
if (status.isOk()) {
StationModel station = (StationModel) w.get(principal,
KEY.STATIONS, stationNumber);
station = new StationModel(station, this.before);
w.set(principal, KEY.STATIONS, stationNumber, station);
}
return status;
}
}
Methods:
MethodJavadoc
doMove
tryDoMove
tryMove
tryUndoMove
undoMove
jfreerails.move.ChangeStationMove
Javadoc:
/** * * This Move changes the properties of a station. * * @author lindsal */
Source code:
/**
*
* This Move changes the properties of a station.
*
* @author lindsal
*/
final public class ChangeStationMove extends ChangeItemInListMove {
private static final long serialVersionUID = 3833469496064160307L;
public ChangeStationMove(int index, StationModel before,
StationModel after, FreerailsPrincipal p) {
super(KEY.STATIONS, index, before, after, p);
}
}
No methods in this class.
jfreerails.move.ChangeTileMove
Javadoc:
/** * Move that changes a single tile. * * @author Luke * */
Source code:
/**
* Move that changes a single tile.
*
* @author Luke
*
*/
public class ChangeTileMove implements Move, MapUpdateMove {
private static final long serialVersionUID = 3256726169272662320L;
private final int x;
private final int y;
private final FreerailsTile before;
private final FreerailsTile after;
public ChangeTileMove(ReadOnlyWorld w, Point p, int terrainTypeAfter) {
this.x = p.x;
this.y = p.y;
this.before = (FreerailsTile) w.getTile(x, y);
this.after = FreerailsTile.getInstance(terrainTypeAfter, before
.getTrackPiece());
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ChangeTileMove))
return false;
final ChangeTileMove changeTileMove = (ChangeTileMove) o;
if (x != changeTileMove.x)
return false;
if (y != changeTileMove.y)
return false;
if (!after.equals(changeTileMove.after))
return false;
if (!before.equals(changeTileMove.before))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = x;
result = 29 * result + y;
result = 29 * result + before.hashCode();
result = 29 * result + after.hashCode();
return result;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
FreerailsTile actual = (FreerailsTile) w.getTile(x, y);
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES, actual
.getTerrainTypeID());
if (!type.getCategory().equals(TerrainType.Category.Country)) {
return MoveStatus.moveFailed("Can only build on clear terrain.");
}
if (actual.equals(before)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + before + " but found "
+ actual);
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
FreerailsTile actual = (FreerailsTile) w.getTile(x, y);
if (actual.equals(after)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + after + " but found "
+ actual);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.isOk()) {
w.setTile(x, y, after);
}
return ms;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.isOk()) {
w.setTile(x, y, before);
}
return ms;
}
public Rectangle getUpdatedTiles() {
Rectangle r = new Rectangle(x, y, 1, 1);
return r;
}
}
Methods:
MethodJavadoc
doMove
getUpdatedTiles/**
tryDoMove
tryUndoMove
undoMove
jfreerails.move.ChangeTrackPieceCompositeMove
Javadoc:
/** * This Move changes adds, removes, or upgrades the track between two tiles. * * @author lindsal * */
Source code:
/**
* This Move changes adds, removes, or upgrades the track between two tiles.
*
* @author lindsal
*
*/
public final class ChangeTrackPieceCompositeMove extends CompositeMove
implements TrackMove, MapUpdateMove {
private static final long serialVersionUID = 3616443518780978743L;
private final int x, y, w, h;
private final FreerailsPrincipal builder;
private ChangeTrackPieceCompositeMove(TrackMove a, TrackMove b,
FreerailsPrincipal fp) {
super(a, b);
Rectangle r = a.getUpdatedTiles().union(b.getUpdatedTiles());
x = r.x;
y = r.y;
w = r.width;
h = r.height;
builder = fp;
}
public static ChangeTrackPieceCompositeMove generateBuildTrackMove(
ImPoint from, Step direction, TrackRule ruleA, TrackRule ruleB,
ReadOnlyWorld w, FreerailsPrincipal principal) {
ChangeTrackPieceMove a;
ChangeTrackPieceMove b;
a = getBuildTrackChangeTrackPieceMove(from, direction, ruleA, w,
principal);
b = getBuildTrackChangeTrackPieceMove(direction
.createRelocatedPoint(from), direction.getOpposite(), ruleB, w,
principal);
return new ChangeTrackPieceCompositeMove(a, b, principal);
}
public static ChangeTrackPieceCompositeMove generateRemoveTrackMove(
ImPoint from, Step direction, ReadOnlyWorld w,
FreerailsPrincipal principal) throws Exception {
TrackMove a;
TrackMove b;
a = getRemoveTrackChangeTrackPieceMove(from, direction, w, principal);
b = getRemoveTrackChangeTrackPieceMove(direction
.createRelocatedPoint(from), direction.getOpposite(), w,
principal);
return new ChangeTrackPieceCompositeMove(a, b, principal);
}
// utility method.
private static ChangeTrackPieceMove getBuildTrackChangeTrackPieceMove(
ImPoint p, Step direction, TrackRule trackRule, ReadOnlyWorld w,
FreerailsPrincipal principal) {
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
int owner = getOwner(principal, w);
if (w.boundsContain(p.x, p.y)) {
oldTrackPiece = ((FreerailsTile) w.getTile(p.x, p.y))
.getTrackPiece();
if (oldTrackPiece.getTrackRule() != NullTrackType.getInstance()) {
TrackConfiguration trackConfiguration = TrackConfiguration.add(
oldTrackPiece.getTrackConfiguration(), direction);
newTrackPiece = new TrackPieceImpl(trackConfiguration,
oldTrackPiece.getTrackRule(), owner, oldTrackPiece
.getTrackTypeID());
} else {
newTrackPiece = getTrackPieceWhenOldTrackPieceIsNull(direction,
trackRule, owner, findRuleID(trackRule, w));
}
} else {
newTrackPiece = getTrackPieceWhenOldTrackPieceIsNull(direction,
trackRule, owner, findRuleID(trackRule, w));
oldTrackPiece = NullTrackPiece.getInstance();
}
return new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece, p);
}
// utility method.
private static TrackMove getRemoveTrackChangeTrackPieceMove(ImPoint p,
Step direction, ReadOnlyWorld w, FreerailsPrincipal principal)
throws Exception {
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
if (w.boundsContain(p.x, p.y)) {
oldTrackPiece = ((FreerailsTile) w.getTile(p.x, p.y)).getTrackPiece();
if (oldTrackPiece.getTrackRule() != NullTrackType.getInstance()) {
TrackConfiguration trackConfiguration = TrackConfiguration
.subtract(oldTrackPiece.getTrackConfiguration(),
direction);
if (trackConfiguration != TrackConfiguration
.getFlatInstance("000010000")) {
int owner = getOwner(principal, w);
newTrackPiece = new TrackPieceImpl(trackConfiguration,
oldTrackPiece.getTrackRule(), owner, oldTrackPiece
.getTrackTypeID());
} else {
newTrackPiece = NullTrackPiece.getInstance();
}
} else {
// There is no track to remove.
// Fix for bug [ 948670 ] Removing non-existent track
throw new Exception();
}
} else {
newTrackPiece = NullTrackPiece.getInstance();
oldTrackPiece = NullTrackPiece.getInstance();
}
ChangeTrackPieceMove m = new ChangeTrackPieceMove(oldTrackPiece,
newTrackPiece, p);
// If we are removing a station, we also need to remove the station from
// the station list.
if (oldTrackPiece.getTrackRule().isStation()
&& !newTrackPiece.getTrackRule().isStation()) {
return RemoveStationMove.getInstance(w, m, principal);
}
return m;
}
private static TrackPiece getTrackPieceWhenOldTrackPieceIsNull(
Step direction, TrackRule trackRule, int owner, int ruleNumber) {
TrackConfiguration simplestConfig = TrackConfiguration
.getFlatInstance("000010000");
TrackConfiguration trackConfiguration = TrackConfiguration.add(
simplestConfig, direction);
return new TrackPieceImpl(trackConfiguration, trackRule, owner,
ruleNumber);
}
public Rectangle getUpdatedTiles() {
return new Rectangle(x, y, w, h);
}
public static int getOwner(FreerailsPrincipal p, ReadOnlyWorld w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
if (w.getPlayer(i).getPrincipal().equals(p)) {
return i;
}
}
throw new IllegalStateException();
}
/** Returns true if some track has been built. */
static boolean hasAnyTrackBeenBuilt(ReadOnlyWorld world,
FreerailsPrincipal principal) {
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
world, principal);
aggregator.setCategory(Transaction.Category.TRACK);
return aggregator.calculateQuantity() > 0;
}
private static boolean mustConnectToExistingTrack(ReadOnlyWorld world) {
GameRules rules = (GameRules) world.get(ITEM.GAME_RULES);
return rules.isMustConnect2ExistingTrack();
}
@Override
protected MoveStatus compositeTest(World world, FreerailsPrincipal p) {
if (mustConnectToExistingTrack(world)) {
if (hasAnyTrackBeenBuilt(world, this.builder)) {
try {
ChangeTrackPieceMove a = (ChangeTrackPieceMove) super
.getMove(0);
ChangeTrackPieceMove b = (ChangeTrackPieceMove) super
.getMove(1);
int ruleBeforeA = a.trackPieceBefore.getTrackTypeID();
int ruleBeforeB = b.trackPieceBefore.getTrackTypeID();
if (ruleBeforeA == NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER
&& ruleBeforeB == NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
return MoveStatus
.moveFailed("Must connect to existing track");
}
} catch (ClassCastException e) {
// It was not the type of move we expected.
// We end up here when we are removing a station.
return MoveStatus.MOVE_OK;
}
}
}
return MoveStatus.MOVE_OK;
}
public static int findRuleID(TrackRule r, ReadOnlyWorld w) {
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
Object o = w.get(SKEY.TRACK_RULES, i);
if (r.equals(o)) {
return i;
}
}
throw new IllegalStateException();
}
}
Methods:
MethodJavadoc
compositeTest
findRuleID
generateBuildTrackMove
generateRemoveTrackMove
getBuildTrackChangeTrackPieceMove
getOwner
getRemoveTrackChangeTrackPieceMove
getTrackPieceWhenOldTrackPieceIsNull
getUpdatedTiles
hasAnyTrackBeenBuilt/** Returns true if some track has been built. */
mustConnectToExistingTrack
jfreerails.move.ChangeTrackPieceMove
Javadoc:
/** * This Move adds, removes, or upgrades the track on a single tile. * * @author Luke * */
Source code:
/**
* This Move adds, removes, or upgrades the track on a single tile.
*
* @author Luke
*
*/
final public class ChangeTrackPieceMove implements TrackMove, MapUpdateMove {
private static final long serialVersionUID = 4120849958418591801L;
final TrackPiece trackPieceBefore;
private final TrackPiece trackPieceAfter;
private final ImPoint location;
public ImPoint getLocation() {
return location;
}
@Override
public int hashCode() {
int result;
result = (trackPieceBefore != null ? trackPieceBefore.hashCode() : 0);
result = 29 * result
+ (trackPieceAfter != null ? trackPieceAfter.hashCode() : 0);
result = 29 * result + location.hashCode();
return result;
}
public TrackPiece getOldTrackPiece() {
return trackPieceBefore;
}
public TrackPiece getNewTrackPiece() {
return trackPieceAfter;
}
public ChangeTrackPieceMove(TrackPiece before, TrackPiece after, ImPoint p) {
trackPieceBefore = before;
trackPieceAfter = after;
location = p;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
return tryMove(w, this.trackPieceBefore, this.trackPieceAfter);
}
private MoveStatus tryMove(World w, TrackPiece oldTrackPiece,
TrackPiece newTrackPiece) {
// Check that location is on the map.
if (!w.boundsContain(location.x, location.y)) {
return MoveStatus
.moveFailed("Tried to build track outside the map.");
}
// Check that we are not changing another players track if this is not
// allowed.
if (!canConnect2OtherRRsTrack(w)) {
// If either the new or old track piece is null, we are ok.
int oldRuleNumber = oldTrackPiece.getTrackTypeID();
int newRuleNumber = newTrackPiece.getTrackTypeID();
if (NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER != oldRuleNumber
&& NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER != newRuleNumber) {
int oldOwner = oldTrackPiece.getOwnerID();
int newOwner = newTrackPiece.getOwnerID();
if (oldOwner != newOwner) {
return MoveStatus
.moveFailed("Not allowed to connect to other RR");
}
}
}
// Check that the current track piece at this.location is
// the same as this.oldTrackPiece.
TrackPiece currentTrackPieceAtLocation = ((FreerailsTile) w.getTile(
location.x, location.y)).getTrackPiece();
TrackRule expectedTrackRule = oldTrackPiece.getTrackRule();
TrackRule actualTrackRule = currentTrackPieceAtLocation.getTrackRule();
if (!expectedTrackRule.equals(actualTrackRule)) {
return MoveStatus.moveFailed("Expected '"
+ expectedTrackRule.getTypeName() + "' but found '"
+ actualTrackRule.getTypeName() + "' at " + location.x
+ " ," + location.y);
}
if (currentTrackPieceAtLocation.getTrackConfiguration() != oldTrackPiece
.getTrackConfiguration()) {
return MoveStatus
.moveFailed("Unexpected track piece found at location: "
+ location.x + " ," + location.y);
}
// Check that oldTrackPiece is not the same as newTrackPiece
if ((oldTrackPiece.getTrackConfiguration() == newTrackPiece
.getTrackConfiguration())
&& (oldTrackPiece.getTrackRule() == newTrackPiece
.getTrackRule())) {
return MoveStatus.moveFailed("Already track here!");
}
// Check for illegal track configurations.
if (!(oldTrackPiece.getTrackRule().trackPieceIsLegal(
oldTrackPiece.getTrackConfiguration()) && newTrackPiece
.getTrackRule().trackPieceIsLegal(
newTrackPiece.getTrackConfiguration()))) {
return MoveStatus.moveFailed("Illegal track configuration.");
}
// Check for diagonal conflicts.
if (!(noDiagonalTrackConflicts(location, oldTrackPiece
.getTrackGraphicID(), w) && noDiagonalTrackConflicts(location,
newTrackPiece.getTrackGraphicID(), w))) {
return MoveStatus
.moveFailed("Illegal track configuration - diagonal conflict");
}
int terrainType = ((FreerailsTile) w.getTile(location.x, location.y))
.getTerrainTypeID();
TerrainType tt = (TerrainType) w.get(SKEY.TERRAIN_TYPES, terrainType);
if (!newTrackPiece.getTrackRule().canBuildOnThisTerrainType(
tt.getCategory())) {
String thisTrackType = newTrackPiece.getTrackRule().getTypeName();
String terrainCategory = tt.getCategory().toString().toLowerCase();
return MoveStatus.moveFailed("Can't build " + thisTrackType
+ " on " + terrainCategory);
}
// Check 4 overlapping stations.
if (newTrackPiece.getTrackRule().isStation()) {
MoveStatus ms = ChangeTrackPieceMove.check4overlap(w, location,
newTrackPiece);
if (!ms.ok)
return ms;
}
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
return tryMove(w, this.trackPieceAfter, this.trackPieceBefore);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus moveStatus = tryDoMove(w, p);
if (!moveStatus.isOk()) {
return moveStatus;
}
move(w, this.trackPieceBefore, this.trackPieceAfter);
return moveStatus;
}
private void move(World w, TrackPiece oldTrackPiece,
TrackPiece newTrackPiece) {
// FIXME why is oldTrackPiece not used???
FreerailsTile oldTile = (FreerailsTile) w.getTile(location.x,
location.y);
int terrain = oldTile.getTerrainTypeID();
FreerailsTile newTile = FreerailsTile.getInstance(terrain,
newTrackPiece);
w.setTile(location.x, location.y, newTile);
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus moveStatus = tryUndoMove(w, p);
if (!moveStatus.isOk()) {
return moveStatus;
}
move(w, this.trackPieceAfter, this.trackPieceBefore);
return moveStatus;
}
private boolean noDiagonalTrackConflicts(ImPoint point, int trackTemplate,
World w) {
/*
* This method is needs replacing. It only deals with flat track pieces,
* and is rather hard to make sense of. LL
*/
// int trackTemplate = (1 << (3 * (1 + tv.getY()) + (1 + tv.getX())));
int trackTemplateAbove;
int trackTemplateBelow;
int cornersTemplate = TrackConfiguration
.stringTemplate2Int("101000101");
trackTemplate = trackTemplate & cornersTemplate;
Dimension mapSize = new Dimension(w.getMapWidth(), w.getMapHeight());
// Avoid array-out-of-bounds exceptions.
if (point.y > 0) {
FreerailsTile ft = (FreerailsTile)w.getTile(point.x, point.y - 1);
TrackPiece tp = ft.getTrackPiece();
trackTemplateAbove = tp.getTrackGraphicID();
} else {
trackTemplateAbove = 0;
}
if ((point.y + 1) < mapSize.height) {
FreerailsTile ft = (FreerailsTile)w.getTile(point.x, point.y + 1);
TrackPiece tp = ft.getTrackPiece();
trackTemplateBelow = tp.getTrackGraphicID();
} else {
trackTemplateBelow = 0;
}
trackTemplateAbove = trackTemplateAbove >> 6;
trackTemplateBelow = trackTemplateBelow << 6;
trackTemplate = trackTemplate
& (trackTemplateAbove | trackTemplateBelow);
if (trackTemplate != 0) {
return false;
// There is a clash.
}
return true;
// Things are ok.
}
public Rectangle getUpdatedTiles() {
// If we are building or removing a station,
// we need to repaint/remove the station radius
// that appears on the map.
int radius = 1;
TrackRule trackRuleAfter = this.trackPieceAfter.getTrackRule();
if (trackRuleAfter.isStation()) {
radius = Math.max(radius, trackRuleAfter.getStationRadius());
}
TrackRule trackRuleBefore = this.trackPieceBefore.getTrackRule();
if (trackRuleBefore.isStation()) {
radius = Math.max(radius, trackRuleBefore.getStationRadius());
}
// Just to be safe.
radius++;
int x;
int y;
int width;
int height;
x = location.x - radius;
y = location.y - radius;
width = radius * 2 + 1;
height = radius * 2 + 1;
return new Rectangle(x, y, width, height);
}
@Override
public boolean equals(Object o) {
if (o instanceof ChangeTrackPieceMove) {
ChangeTrackPieceMove m = (ChangeTrackPieceMove) o;
boolean fieldPointEqual = this.location.equals(m.location);
boolean fieldoldTrackPieceEqual = this.trackPieceBefore
.equals(m.trackPieceBefore);
boolean fieldnewTrackPieceEqual = this.trackPieceAfter
.equals(m.trackPieceAfter);
if (fieldPointEqual && fieldoldTrackPieceEqual
&& fieldnewTrackPieceEqual) {
return true;
}
return false;
}
return false;
}
protected static boolean canConnect2OtherRRsTrack(ReadOnlyWorld world) {
GameRules rules = (GameRules) world.get(ITEM.GAME_RULES);
return rules.isCanConnect2OtherRRTrack();
}
/**
* This method may be called under 3 possible conditions: (1) when a station
* is getting built, (2) when a station is getting upgraded, (3) when a
* station is getting removed.
*/
protected static MoveStatus check4overlap(World w, ImPoint location,
TrackPiece trackPiece) {
/*
* Fix for 915945 (Stations should not overlap) Check that there is not
* another station whose radius overlaps with the one we are building.
*/
TrackRule thisStationType = trackPiece.getTrackRule();
assert thisStationType.isStation();
for (int player = 0; player < w.getNumberOfPlayers(); player++) {
FreerailsPrincipal principal = w.getPlayer(player).getPrincipal();
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
while (wi.next()) {
StationModel station = (StationModel) wi.getElement();
/*
* Fix for bug 948675 - Can't upgrade station types If locations
* are the same, then we are upgrading a station so it doesn't
* matter if the radii overlap.
*/
if (location.x == station.x && location.y == station.y) {
continue;
}
FreerailsTile tile = (FreerailsTile) w.getTile(station.x,
station.y);
TrackRule otherStationType = tile.getTrackPiece().getTrackRule();
assert otherStationType.isStation();
int sumOfRadii = otherStationType.getStationRadius()
+ thisStationType.getStationRadius();
int sumOfRadiiSquared = sumOfRadii * sumOfRadii;
int xDistance = station.x - location.x;
int yDistance = station.y - location.y;
// Do radii overlap?
boolean xOverlap = sumOfRadiiSquared >= (xDistance * xDistance);
boolean yOverlap = sumOfRadiiSquared >= (yDistance * yDistance);
if (xOverlap && yOverlap) {
String message = "Too close to " + station.getStationName();
return MoveStatus.moveFailed(message);
}
}
}
return MoveStatus.MOVE_OK;
}
}
Methods:
MethodJavadoc
canConnect2OtherRRsTrack
check4overlap/**
doMove
getLocation
getNewTrackPiece
getOldTrackPiece
getUpdatedTiles
move
noDiagonalTrackConflicts
tryDoMove
tryMove
tryUndoMove
undoMove
jfreerails.move.ChangeTrainMove
Javadoc:
/** * This Move can change a train's engine and wagons. * * @author Luke Lindsay * */
Source code:
/**
* This Move can change a train's engine and wagons.
*
* @author Luke Lindsay
*
*/
public class ChangeTrainMove extends ChangeItemInListMove {
private static final long serialVersionUID = 3257854272514242873L;
private ChangeTrainMove(int index, FreerailsSerializable before,
FreerailsSerializable after, FreerailsPrincipal p) {
super(KEY.TRAINS, index, before, after, p);
}
public static ChangeTrainMove generateMove(int id, TrainModel before,
int newEngine, ImInts newWagons, FreerailsPrincipal p) {
TrainModel after = before.getNewInstance(newEngine, newWagons);
return new ChangeTrainMove(id, before, after, p);
}
}
Methods:
MethodJavadoc
generateMove
jfreerails.move.ChangeTrainScheduleMove
Javadoc:
/** * This Move changes a train's schedule. * * @author Luke Lindsay * */
Source code:
/**
* This Move changes a train's schedule.
*
* @author Luke Lindsay
*
*/
public class ChangeTrainScheduleMove extends ChangeItemInListMove {
private static final long serialVersionUID = 3691043187930052149L;
public ChangeTrainScheduleMove(int id, ImmutableSchedule before,
ImmutableSchedule after, FreerailsPrincipal p) {
super(KEY.TRAIN_SCHEDULES, id, before, after, p);
}
}
No methods in this class.
jfreerails.move.CompositeMove
Javadoc:
/** * * This Move may be subclassed to create a move composed of a number of * component Moves where atomicity of the move is required. This class defines a * number of methods which may not be subclassed - all changes must be * encapsulated as sub-moves of this move. * * @author Luke */
Source code:
/**
*
* This Move may be subclassed to create a move composed of a number of
* component Moves where atomicity of the move is required. This class defines a
* number of methods which may not be subclassed - all changes must be
* encapsulated as sub-moves of this move.
*
* @author Luke
*/
public class CompositeMove implements Move {
private static final long serialVersionUID = 3257289149391517489L;
private final ImList<Move> moves;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof CompositeMove))
return false;
final CompositeMove compositeMove = (CompositeMove) o;
if (!moves.equals(compositeMove.moves))
return false;
return true;
}
/**
* This method lets sub classes look at the moves.
*/
final Move getMove(int i) {
return moves.get(i);
}
@Override
public int hashCode() {
// This will do for now.
return moves.size();
}
public final ImList<Move> getMoves() {
return moves;
}
public CompositeMove(List<Move> movesArrayList) {
moves = new ImList<Move>(movesArrayList);
}
public CompositeMove(Move... moves) {
this.moves = new ImList<Move>(moves);
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
// Since whether a move later in the list goes through could
// depend on whether an earlier move has been executed, we need
// actually execute moves, then undo them to test whether the
// array of moves can be executed ok.
MoveStatus ms = doMove(w, p);
if (ms.ok) {
// We just wanted to see if we could do them so we undo them again.
undoMoves(w, moves.size() - 1, p);
}
// If its not ok, then doMove would have undone the moves so we don't
// need to undo them.
return ms;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = undoMove(w, p);
if (ms.isOk()) {
redoMoves(w, 0, p);
}
return ms;
}
public final MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = compositeTest(w, p);
if (!ms.ok) {
return ms;
}
for (int i = 0; i < moves.size(); i++) {
ms = moves.get(i).doMove(w, p);
if (!ms.ok) {
// Undo any moves we have already done.
undoMoves(w, i - 1, p);
return ms;
}
}
return ms;
}
public final MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = MoveStatus.MOVE_OK;
for (int i = moves.size() - 1; i >= 0; i--) {
ms = moves.get(i).undoMove(w, p);
if (!ms.ok) {
// Redo any moves we have already undone.
redoMoves(w, i + 1, p);
return ms;
}
}
return ms;
}
private void undoMoves(World w, int number, FreerailsPrincipal p) {
for (int i = number; i >= 0; i--) {
MoveStatus ms = moves.get(i).undoMove(w, p);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
}
}
private void redoMoves(World w, int number, FreerailsPrincipal p) {
for (int i = number; i < moves.size(); i++) {
MoveStatus ms = moves.get(i).doMove(w, p);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
}
}
/**
* Subclasses may override this method to perform tests which pass or fail
* depending on the combination of moves making up this composite move.
*/
MoveStatus compositeTest(World w, FreerailsPrincipal p) {
return MoveStatus.MOVE_OK;
}
public int size(){
return moves.size();
}
@Override
public final String toString() {
String s = "";
for (int i = 0; i < moves.size(); i++) {
s += moves.get(i).toString() + ((i > 0) ? ", " : "");
}
return s;
}
}
Methods:
MethodJavadoc
compositeTest/**
doMove
getMove/**
getMoves
redoMoves
size
tryDoMove
tryUndoMove
undoMove
undoMoves
jfreerails.move.ListMove
Javadoc:
/** * This interface provides information about changes to the lists in the World * database. * * @author rob? */
Source code:
/**
* This interface provides information about changes to the lists in the World
* database.
*
* @author rob?
*/
public interface ListMove extends Move {
/**
* @return the type of object which was changed
*/
KEY getKey();
/**
* @return the old item or null if not any.
*/
FreerailsSerializable getBefore();
/**
* @return the new item or null if not any.
*/
FreerailsSerializable getAfter();
/**
* @return the index of the item which changed.
*/
int getIndex();
FreerailsPrincipal getPrincipal();
}
Methods:
MethodJavadoc
getAfter/**
getBefore/**
getIndex/**
getKey/**
getPrincipal
jfreerails.move.MapUpdateMove
Javadoc:
/** * This interface tags Moves that change items on the map and tells the caller * which tiles have been updated. It is used by the map-view classes to * determine which tiles need repainting. * * @author Luke * */
Source code:
/**
* This interface tags Moves that change items on the map and tells the caller
* which tiles have been updated. It is used by the map-view classes to
* determine which tiles need repainting.
*
* @author Luke
*
*/
public interface MapUpdateMove extends Move {
Rectangle getUpdatedTiles();
}
Methods:
MethodJavadoc
getUpdatedTiles
jfreerails.move.Move
Javadoc:
/** * All moves should implement this interface and obey the contract described * below. * <p> * (1) They should be immutable. * </P> * <p> * (2) They should override <code>Object.equals()</code> to test for logical * equality. * </P> * <p> * (3) They should store 'before' and 'after' values for all properties of the * world object that they change. * <p> * (4) The changes they encapsulate should be stored in an address space * independent way, so that a move generated on a client can be serialised, sent * over a network, and then deserialized and executed on a server. To achieve * this, they should refer to items in the game world via either their * coordinates, e.g. tile 10,50, or their position in a list, e.g. train #4. * </p> * <p> * (5) They should be undoable. To achieve this, they need to store the * information necessary to undo the change. E.g. a change-terrain-type move * might store the tile coordinates, the terrain type before the change and the * terrain type after the change. * </p> * <p> * (6) The tryDoMove and tryUndoMove methods should test whether the move is * valid but leave the gameworld unchanged * </p> * * @see MoveStatus * @see jfreerails.world.top.World * @see jfreerails.controller.PreMove * @author lindsal */
Source code:
/**
* All moves should implement this interface and obey the contract described
* below.
* <p>
* (1) They should be immutable.
* </P>
* <p>
* (2) They should override <code>Object.equals()</code> to test for logical
* equality.
* </P>
* <p>
* (3) They should store 'before' and 'after' values for all properties of the
* world object that they change.
* <p>
* (4) The changes they encapsulate should be stored in an address space
* independent way, so that a move generated on a client can be serialised, sent
* over a network, and then deserialized and executed on a server. To achieve
* this, they should refer to items in the game world via either their
* coordinates, e.g. tile 10,50, or their position in a list, e.g. train #4.
* </p>
* <p>
* (5) They should be undoable. To achieve this, they need to store the
* information necessary to undo the change. E.g. a change-terrain-type move
* might store the tile coordinates, the terrain type before the change and the
* terrain type after the change.
* </p>
* <p>
* (6) The tryDoMove and tryUndoMove methods should test whether the move is
* valid but leave the gameworld unchanged
* </p>
*
* @see MoveStatus
* @see jfreerails.world.top.World
* @see jfreerails.controller.PreMove
* @author lindsal
*/
public interface Move extends FreerailsSerializable {
/**
* Tests whether this Move can be executed on the specified world object,
* this method should leave the world object unchanged.
*/
MoveStatus tryDoMove(World w, FreerailsPrincipal p);
/**
* Tests whether this Move can be undone on the specified world object, this
* method should leave the world object unchanged.
*/
MoveStatus tryUndoMove(World w, FreerailsPrincipal p);
/**
* Executes this move on the specified world object.
*/
MoveStatus doMove(World w, FreerailsPrincipal p);
/**
* If <code>doMove</code> has just been executed on the specified world
* object, calling this method changes the state of the world object back to
* how it was before <code>doMove</code> was called.
*/
MoveStatus undoMove(World w, FreerailsPrincipal p);
}
Methods:
MethodJavadoc
doMove/**
tryDoMove/**
tryUndoMove/**
undoMove/**
jfreerails.move.MoveStatus
Javadoc:
/** * Records the success or failure of an attempt to execute a move. * * @author lindsal */
Source code:
/**
* Records the success or failure of an attempt to execute a move.
*
* @author lindsal
*/
@Immutable
final public class MoveStatus implements FreerailsSerializable {
private static final long serialVersionUID = 3258129171879309624L;
public static final MoveStatus MOVE_OK = new MoveStatus(true,
"Move accepted");
public final boolean ok;
public final String message;
private final Throwable t;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof MoveStatus))
return false;
final MoveStatus moveStatus = (MoveStatus) o;
if (ok != moveStatus.ok)
return false;
if (message != null ? !message.equals(moveStatus.message)
: moveStatus.message != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = (ok ? 1 : 0);
result = 29 * result + (message != null ? message.hashCode() : 0);
return result;
}
/**
* Avoid creating a duplicate when deserializing.
*/
private Object readResolve() {
if (ok) {
return MOVE_OK;
}
return this;
}
private MoveStatus(boolean ok, String mess) {
if(ok){
t = null;
}else{
t = new Throwable();
t.fillInStackTrace();
}
this.ok = ok;
this.message = mess;
}
public static MoveStatus moveFailed(String reason) {
return new MoveStatus(false, reason);
}
public boolean isOk() {
return ok;
}
public void printStackTrack(){
if(null != t)
t.printStackTrace();
}
@Override
public String toString() {
return message;
}
}
Methods:
MethodJavadoc
isOk
moveFailed
printStackTrack
readResolve/**
jfreerails.move.NextActivityMove
Javadoc:
/** * Represents a move to advance to the next activity in a sequence for a given principal. * This class encapsulates the logic for performing and undoing the move, ensuring * validity through the MoveStatus enum. It is responsible for managing activity transitions * within a world state. * * @author John Doe * @see Move * @see Activity * @see FreerailsPrincipal * @see World */
Source code:
public class NextActivityMove implements Move {
private static final long serialVersionUID = -1783556069173689661L;
private final Activity activity;
private final FreerailsPrincipal principal;
private final int index;
public NextActivityMove(Activity activity, int index,
FreerailsPrincipal principal) {
this.activity = activity;
this.index = index;
this.principal = principal;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof NextActivityMove))
return false;
final NextActivityMove nextActivityMove = (NextActivityMove) o;
if (index != nextActivityMove.index)
return false;
if (!activity.equals(nextActivityMove.activity))
return false;
if (!principal.equals(nextActivityMove.principal))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = activity.hashCode();
result = 29 * result + principal.hashCode();
result = 29 * result + index;
return result;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
// Check that active entity exists.
if (w.size(principal) <= index)
return MoveStatus.moveFailed("Index out of range. "+w.size(principal)+"<= "+index);
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
ActivityIterator ai = w.getActivities(principal, index);
ai.gotoLastActivity();
Activity act = ai.getActivity();
if (act.equals(activity))
return MoveStatus.MOVE_OK;
return MoveStatus.moveFailed("Expected " + activity + " but found "
+ act);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.ok)
w.add(principal, index, activity);
return ms;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.ok)
w.removeLastActivity(principal, index);
return ms;
}
}
Methods:
MethodJavadoc
doMove
tryDoMove
tryUndoMove
undoMove
jfreerails.move.PreMoveException
Javadoc:
/** * Thrown when there is a problem generating a move. * * @author Luke Lindsay * * */
Source code:
/**
* Thrown when there is a problem generating a move.
*
* @author Luke Lindsay
*
*
*/
public class PreMoveException extends Exception {
private static final long serialVersionUID = 3257007635675755061L;
public PreMoveException(String s) {
super(s);
}
}
No methods in this class.
jfreerails.move.RemoveCargoBundleMove
Javadoc:
/** * This move removes a cargo bundle from the cargo bundle list. * * @author Luke * */
Source code:
/**
* This move removes a cargo bundle from the cargo bundle list.
*
* @author Luke
*
*/
public class RemoveCargoBundleMove extends RemoveItemFromListMove {
private static final long serialVersionUID = 3762247522239723316L;
public RemoveCargoBundleMove(int i, ImmutableCargoBundle item,
FreerailsPrincipal p) {
super(KEY.CARGO_BUNDLES, i, item, p);
}
}
No methods in this class.
jfreerails.move.RemoveItemFromListMove
Javadoc:
/** * All moves that remove an item from a list should extend this class. * * @author Luke * */
Source code:
/**
* All moves that remove an item from a list should extend this class.
*
* @author Luke
*
*/
public class RemoveItemFromListMove implements ListMove {
private static final long serialVersionUID = 3906091169698953521L;
private final FreerailsSerializable item;
private final KEY listKey;
private final int index;
private final FreerailsPrincipal principal;
public int getIndex() {
return index;
}
@Override
public int hashCode() {
int result;
result = (item != null ? item.hashCode() : 0);
result = 29 * result + listKey.hashCode();
result = 29 * result + index;
result = 29 * result + principal.hashCode();
return result;
}
public KEY getKey() {
return listKey;
}
RemoveItemFromListMove(KEY k, int i, FreerailsSerializable item,
FreerailsPrincipal p) {
this.item = item;
this.listKey = k;
this.index = i;
this.principal = p;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.size(principal, listKey) < (index + 1)) {
return MoveStatus.moveFailed("w.size(listKey)="
+ w.size(principal, listKey) + " but index =" + index);
}
FreerailsSerializable item2remove = w.get(principal, listKey, index);
if (null == item2remove) {
return MoveStatus.moveFailed("The item at position " + index
+ " has already been removed.");
}
if (!item.equals(item2remove)) {
String reason = "The item at position " + index + " in the list ("
+ item2remove.toString() + ") is not the expected item ("
+ item.toString() + ").";
return MoveStatus.moveFailed(reason);
}
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
if (w.size(principal, listKey) < (index + 1)) {
return MoveStatus.moveFailed("w.size(listKey)="
+ w.size(principal, listKey) + " but index =" + index);
}
if (null != w.get(principal, listKey, index)) {
String reason = "The item at position " + index + " in the list ("
+ w.get(principal, listKey, index).toString()
+ ") is not the expected item (null).";
return MoveStatus.moveFailed(reason);
}
return MoveStatus.MOVE_OK;
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.isOk()) {
w.set(principal, listKey, index, null);
}
return ms;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.isOk()) {
w.set(principal, listKey, index, this.item);
}
return ms;
}
@Override
public boolean equals(Object o) {
if (o instanceof RemoveItemFromListMove) {
RemoveItemFromListMove test = (RemoveItemFromListMove) o;
if (!this.item.equals(test.getBefore())) {
return false;
}
if (this.index != test.index) {
return false;
}
if (this.listKey != test.listKey) {
return false;
}
return true;
}
return false;
}
public FreerailsSerializable getBefore() {
return item;
}
public FreerailsSerializable getAfter() {
return null;
}
public FreerailsPrincipal getPrincipal() {
return principal;
}
}
Methods:
MethodJavadoc
doMove
getAfter
getBefore
getIndex
getKey
getPrincipal
tryDoMove
tryUndoMove
undoMove
jfreerails.move.RemoveStationMove
Javadoc:
/** * This Move removes a station from the station list and from the map. * * @author Luke * */
Source code:
/**
* This Move removes a station from the station list and from the map.
*
* @author Luke
*
*/
public class RemoveStationMove extends CompositeMove implements TrackMove {
private static final long serialVersionUID = 3760847865429702969L;
private RemoveStationMove(ArrayList<Move> moves) {
super(moves);
}
static RemoveStationMove getInstance(ReadOnlyWorld w,
ChangeTrackPieceMove removeTrackMove, FreerailsPrincipal principal) {
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
int stationIndex = -1;
while (wi.next()) {
StationModel station = (StationModel) wi.getElement();
if (station.x == removeTrackMove.getLocation().x
&& station.y == removeTrackMove.getLocation().y) {
// We have found the station!
stationIndex = wi.getIndex();
break;
}
}
if (-1 == stationIndex) {
throw new IllegalArgumentException("Could find a station at "
+ removeTrackMove.getLocation().x + ", "
+ removeTrackMove.getLocation().y);
}
StationModel station2remove = (StationModel) w.get(principal,
KEY.STATIONS, stationIndex);
ArrayList<Move> moves = new ArrayList<Move>();
moves.add(removeTrackMove);
moves.add(new RemoveItemFromListMove(KEY.STATIONS, stationIndex,
station2remove, principal));
// Now update any train schedules that include this station.
WorldIterator schedules = new NonNullElements(KEY.TRAIN_SCHEDULES, w,
principal);
while (schedules.next()) {
ImmutableSchedule schedule = (ImmutableSchedule) schedules
.getElement();
if (schedule.stopsAtStation(stationIndex)) {
MutableSchedule mutableSchedule = new MutableSchedule(schedule);
mutableSchedule.removeAllStopsAtStation(stationIndex);
Move changeScheduleMove = new ChangeTrainScheduleMove(schedules
.getIndex(), schedule, mutableSchedule
.toImmutableSchedule(), principal);
moves.add(changeScheduleMove);
}
}
return new RemoveStationMove(moves);
}
public Rectangle getUpdatedTiles() {
TrackMove tm = (TrackMove) getMove(0);
return tm.getUpdatedTiles();
}
}
Methods:
MethodJavadoc
getInstance
getUpdatedTiles
jfreerails.move.RemoveTrainMove
Javadoc:
/** * This Move removes a train from the list of trains, and the corresponding * CargoBundle and Schedule. * * @author Luke * */
Source code:
/**
* This Move removes a train from the list of trains, and the corresponding
* CargoBundle and Schedule.
*
* @author Luke
*
*/
public class RemoveTrainMove extends CompositeMove {
private static final long serialVersionUID = 3979265867567544114L;
private RemoveTrainMove(Move[] moves) {
super(moves);
}
public static RemoveTrainMove getInstance(int index, FreerailsPrincipal p,
ReadOnlyWorld world) {
TrainModel train = (TrainModel) world.get(p, KEY.TRAINS, index);
int scheduleId = train.getScheduleID();
ImmutableSchedule schedule = (ImmutableSchedule) world.get(
p, KEY.TRAIN_SCHEDULES, scheduleId);
int cargoBundleId = train.getCargoBundleID();
ImmutableCargoBundle cargoBundle = (ImmutableCargoBundle) world.get(
p, KEY.CARGO_BUNDLES, cargoBundleId);
// TrainPositionOnMap position =
// (TrainPositionOnMap)world.get(KEY.TRAIN_POSITIONS, index, p);
Move removeTrain = new RemoveItemFromListMove(KEY.TRAINS, index, train,
p);
Move removeCargobundle = new RemoveItemFromListMove(KEY.CARGO_BUNDLES,
cargoBundleId, cargoBundle, p);
Move removeSchedule = new RemoveItemFromListMove(KEY.TRAIN_SCHEDULES,
scheduleId, schedule, p);
// Move removePosition = new RemoveItemFromListMove(KEY.TRAIN_POSITIONS,
// index, position, p);
return new RemoveTrainMove(new Move[] { removeTrain, removeCargobundle,
removeSchedule /* , removePosition */
});
}
}
Methods:
MethodJavadoc
getInstance
jfreerails.move.ServerMove
Javadoc:
/** * Indicates a move which can only be submitted by the server. * * @author rob */
Source code:
/**
* Indicates a move which can only be submitted by the server.
*
* @author rob
*/
public interface ServerMove {
}
No methods in this class.
jfreerails.move.TimeTickMove
Javadoc:
/** * * Changes the time item on the world object. * * @author rob */
Source code:
/**
*
* Changes the time item on the world object.
*
* @author rob
*/
public class TimeTickMove implements Move {
private static final long serialVersionUID = 3257290240212153393L;
private final GameTime oldTime;
private final GameTime newTime;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TimeTickMove))
return false;
final TimeTickMove timeTickMove = (TimeTickMove) o;
if (!newTime.equals(timeTickMove.newTime))
return false;
if (!oldTime.equals(timeTickMove.oldTime))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = oldTime.hashCode();
result = 29 * result + newTime.hashCode();
return result;
}
public static TimeTickMove getMove(ReadOnlyWorld w) {
GameTime oldTime = w.currentTime();
GameTime newTime = new GameTime(oldTime.getTicks() + 1);
return new TimeTickMove(oldTime, newTime);
}
public TimeTickMove(GameTime oldTime, GameTime newTime) {
this.oldTime = oldTime;
this.newTime = newTime;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.currentTime().equals(oldTime)) {
return MoveStatus.MOVE_OK;
}
String string = "oldTime = " + oldTime.getTicks() + " <=> "
+ "currentTime " + (w.currentTime()).getTicks();
return MoveStatus.moveFailed(string);
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
GameTime time = w.currentTime();
if (time.equals(newTime)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + newTime + ", found " + time);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryDoMove(w, p);
if (status.ok) {
w.setTime(newTime);
}
return status;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryUndoMove(w, p);
if (status.isOk()) {
w.setTime(oldTime);
}
return status;
}
@Override
public String toString() {
return "TimeTickMove: " + oldTime + "=>" + newTime;
}
}
Methods:
MethodJavadoc
doMove
getMove
tryDoMove
tryUndoMove
undoMove
jfreerails.move.TrackMove
Javadoc:
/** * This interface tags Moves that change the track. * * @author luke */
Source code:
/**
* This interface tags Moves that change the track.
*
* @author luke
*/
public interface TrackMove extends MapUpdateMove {
}
No methods in this class.
jfreerails.move.TrackMoveTransactionsGenerator
Javadoc:
/** * This class calculates the cost of a series of track moves. The motivation for * separating this code from the code that generates track moves is that the * transactions will be generated by the server whereas the track moves will be * generated by a client. * * @author Luke Lindsay * */
Source code:
/**
* This class calculates the cost of a series of track moves. The motivation for
* separating this code from the code that generates track moves is that the
* transactions will be generated by the server whereas the track moves will be
* generated by a client.
*
* @author Luke Lindsay
*
*/
public class TrackMoveTransactionsGenerator {
/** Number of each of the track types added. */
private int[] trackAdded;
private long fixedCostsStations = 0;
private long fixedCostsBridges = 0;
/** Number of each of the track types removed. */
private int[] trackRemoved;
private final FreerailsPrincipal principal;
/*
* Note, trackAdded and trackRemoved cannot be combined, since it may cost
* more to added a unit of track than is refunded when you removed it.
*/
private final ArrayList<Transaction> transactions = new ArrayList<Transaction>();
private final ReadOnlyWorld w;
/**
* @param p
* the Principal on behalf of which this object generates
* transactions for
*/
public TrackMoveTransactionsGenerator(ReadOnlyWorld world,
FreerailsPrincipal p) {
w = world;
principal = p;
}
public CompositeMove addTransactions(Move move) {
int numberOfTrackTypes = w.size(SKEY.TRACK_RULES);
trackAdded = new int[numberOfTrackTypes];
trackRemoved = new int[numberOfTrackTypes];
fixedCostsStations = 0;
fixedCostsBridges = 0;
unpackMove(move);
generateTransactions();
int numberOfMoves = 1 + transactions.size();
Move[] moves = new Move[numberOfMoves];
moves[0] = move;
for (int i = 0; i < transactions.size(); i++) {
Transaction t = transactions.get(i);
moves[i + 1] = new AddTransactionMove(principal, t, true);
}
return new CompositeMove(moves);
}
private void unpackMove(Move move) {
if (move instanceof ChangeTrackPieceMove) {
ChangeTrackPieceMove tm = (ChangeTrackPieceMove) move;
processMove(tm);
} else if (move instanceof CompositeMove) {
CompositeMove cm = (CompositeMove) move;
cm.getMoves();
ImList<Move> moves = cm.getMoves();
for (int i = 0; i < moves.size(); i++) {
unpackMove(moves.get(i));
}
}
}
private void processMove(ChangeTrackPieceMove move) {
TrackPiece newTrackPiece = move.getNewTrackPiece();
TrackRule newTrackRule = newTrackPiece.getTrackRule();
final int ruleAfter = newTrackPiece.getTrackTypeID();
TrackPiece oldTrackPiece = move.getOldTrackPiece();
final int ruleBefore = oldTrackPiece.getTrackTypeID();
final int oldLength = oldTrackPiece.getTrackConfiguration().getLength();
final int newLength = newTrackPiece.getTrackConfiguration().getLength();
if (ruleAfter != ruleBefore) {
TrackRule.TrackCategories category = newTrackRule.getCategory();
switch (category) {
case station: {
fixedCostsStations -= newTrackRule.getFixedCost().getAmount();
break;
}
case bridge: {
fixedCostsBridges -= newTrackRule.getFixedCost().getAmount();
break;
}
default: {
// Do nothing.
}
}
}
if (ruleAfter == ruleBefore) {
if (oldLength < newLength) {
trackAdded[ruleAfter] += (newLength - oldLength);
} else if (oldLength > newLength) {
trackRemoved[ruleAfter] += (oldLength - newLength);
}
return;
}
if (ruleAfter != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
trackAdded[ruleAfter] += newLength;
}
if (ruleBefore != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
trackRemoved[ruleBefore] += oldLength;
}
}
private void generateTransactions() {
transactions.clear();
// For each track type, generate a transaction if any pieces of the type
// have been added or removed.
for (int i = 0; i < trackAdded.length; i++) {
int numberAdded = trackAdded[i];
if (0 != numberAdded) {
TrackRule rule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
Money m = rule.getPrice();
Money total = new Money(-m.getAmount() * numberAdded
/ TrackConfiguration.LENGTH_OF_STRAIGHT_TRACK_PIECE);
Transaction t = new AddItemTransaction(TRACK, i, numberAdded,
total);
transactions.add(t);
}
int numberRemoved = trackRemoved[i];
if (0 != numberRemoved) {
TrackRule rule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
Money m = rule.getPrice();
Money total = new Money((m.getAmount() * numberRemoved)
/ TrackConfiguration.LENGTH_OF_STRAIGHT_TRACK_PIECE);
// You only get half the money back.
total = new Money(total.getAmount() / 2);
Transaction t = new AddItemTransaction(TRACK, i,
-numberRemoved, total);
transactions.add(t);
}
}
if (0 != fixedCostsStations) {
Transaction t = new AddItemTransaction(STATIONS, -1, -1, new Money(
fixedCostsStations));
transactions.add(t);
}
if (0 != fixedCostsBridges) {
Transaction t = new AddItemTransaction(BRIDGES, -1, -1, new Money(
fixedCostsBridges));
transactions.add(t);
}
}
}
Methods:
MethodJavadoc
addTransactions
generateTransactions
processMove
unpackMove
jfreerails.move.TrainCrashException
Javadoc:
/** * * @author mduarte-leon */
Source code:
/**
*
* @author mduarte-leon
*/
public class TrainCrashException extends Exception {
private static final long serialVersionUID = 3978710596948342065L;
private int trainA;
private int trainB;
public TrainCrashException() {
}
public TrainCrashException(int aTrain, int bTrain) {
trainA = aTrain;
trainB = bTrain;
}
public int getTrainA() {
return trainA;
}
public int getTrainB() {
return trainB;
}
}
Methods:
MethodJavadoc
getTrainA
getTrainB
jfreerails.move.TransferCargoAtStationMove
Javadoc:
/** * This {@link CompositeMove} transfers cargo from a train to a station and * vice-versa. * * @author Luke Lindsay * * */
Source code:
/**
* This {@link CompositeMove} transfers cargo from a train to a station and
* vice-versa.
*
* @author Luke Lindsay
*
*
*/
public class TransferCargoAtStationMove extends CompositeMove {
private static final long serialVersionUID = 3257291318215456563L;
public static final int CHANGE_ON_TRAIN_INDEX = 1;
public static final int CHANGE_AT_STATION_INDEX = 0;
private final boolean waitingForFullLoad;
private TransferCargoAtStationMove(Move[] moves, boolean waiting) {
super(moves);
waitingForFullLoad = waiting;
}
public static TransferCargoAtStationMove generateMove(
ChangeCargoBundleMove changeAtStation,
ChangeCargoBundleMove changeOnTrain, CompositeMove payment,
boolean waiting) {
return new TransferCargoAtStationMove(new Move[] { changeAtStation,
changeOnTrain, payment }, waiting);
}
public ChangeCargoBundleMove getChangeAtStation() {
return (ChangeCargoBundleMove) super.getMoves().get(
CHANGE_AT_STATION_INDEX);
}
public ChangeCargoBundleMove getChangeOnTrain() {
return (ChangeCargoBundleMove) super.getMoves().get(
CHANGE_ON_TRAIN_INDEX);
}
public Money getRevenue() {
ImList<Move> moves = super.getMoves();
long amount = CHANGE_AT_STATION_INDEX;
for (int i = CHANGE_AT_STATION_INDEX; i < moves.size(); i++) {
if (moves.get(i) instanceof AddTransactionMove) {
AddTransactionMove move = (AddTransactionMove) moves.get(i);
DeliverCargoReceipt receipt = (DeliverCargoReceipt) move
.getTransaction();
amount += receipt.deltaCash().getAmount();
}
}
return new Money(amount);
}
public int getQuantityOfCargo(int cargoType) {
ImList<Move> moves = super.getMoves();
int quantity = CHANGE_AT_STATION_INDEX;
for (int i = CHANGE_AT_STATION_INDEX; i < moves.size(); i++) {
if (moves.get(i) instanceof AddTransactionMove) {
AddTransactionMove move = (AddTransactionMove) moves.get(i);
DeliverCargoReceipt receipt = (DeliverCargoReceipt) move
.getTransaction();
CargoBatch cb = receipt.getCb();
if (cb.getCargoType() == cargoType) {
quantity += receipt.getQuantity();
}
}
}
return quantity;
}
/** The player who is getting paid for the delivery. */
public FreerailsPrincipal getPrincipal() {
ImList<Move> moves = super.getMoves();
for (int i = CHANGE_AT_STATION_INDEX; i < moves.size(); i++) {
if (moves.get(i) instanceof AddTransactionMove) {
AddTransactionMove move = (AddTransactionMove) moves.get(i);
return move.getPrincipal();
}
}
return Player.NOBODY;
}
public TransferCargoAtStationMove(ArrayList<Move> movesArrayList,
boolean waiting) {
super(movesArrayList);
this.waitingForFullLoad = waiting;
}
public boolean isWaitingForFullLoad() {
return waitingForFullLoad;
}
}
Methods:
MethodJavadoc
generateMove
getChangeAtStation
getChangeOnTrain
getPrincipal/** The player who is getting paid for the delivery. */
getQuantityOfCargo
getRevenue
isWaitingForFullLoad
jfreerails.move.UndoMove
Javadoc:
/** * Undoes the Move passed to its constructor. * * @author luke */
Source code:
/**
* Undoes the Move passed to its constructor.
*
* @author luke
*/
public class UndoMove implements Move {
private static final long serialVersionUID = 3977582498051929144L;
private Move move2undo;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof UndoMove))
return false;
final UndoMove undoMove = (UndoMove) o;
if (!move2undo.equals(undoMove.move2undo))
return false;
return true;
}
@Override
public int hashCode() {
return move2undo.hashCode();
}
/**
* @param move
* The move that was undone
*/
public UndoMove(Move move) {
if (move instanceof UndoMove) {
throw new IllegalArgumentException();
}
move2undo = move;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
return move2undo.tryUndoMove(w, p);
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
return move2undo.tryDoMove(w, p);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
return move2undo.undoMove(w, p);
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
return move2undo.undoMove(w, p);
}
public Move getUndoneMove() {
return move2undo;
}
}
Methods:
MethodJavadoc
doMove
getUndoneMove
tryDoMove
tryUndoMove
undoMove
jfreerails.move.UpgradeTrackMove
Javadoc:
/** * This CompositeMove changes the track type at a point on the map and charges * the players account for the cost of the change. * * @author Luke Lindsay * */
Source code:
/**
* This CompositeMove changes the track type at a point on the map and charges
* the players account for the cost of the change.
*
* @author Luke Lindsay
*
*/
public class UpgradeTrackMove extends CompositeMove implements TrackMove {
private static final long serialVersionUID = 3907215961470875442L;
private UpgradeTrackMove(ChangeTrackPieceMove trackMove) {
super(trackMove);
}
public static UpgradeTrackMove generateMove(TrackPiece before,
TrackPiece after, ImPoint p) {
ChangeTrackPieceMove m = new ChangeTrackPieceMove(before, after, p);
return new UpgradeTrackMove(m);
}
public Rectangle getUpdatedTiles() {
ChangeTrackPieceMove m = (ChangeTrackPieceMove) this.getMove(0);
return m.getUpdatedTiles();
}
}
Methods:
MethodJavadoc
generateMove
getUpdatedTiles
jfreerails.move.WorldDiffMove
Javadoc:
/** * A move that makes a number of changes to the map and to the lists. * * WARNING: This class currently only handles the most common cases. A * UnsupportedOperationException is thrown if an appropriate move * cannot be generated. * * * @author Luke */
Source code:
/**
* A move that makes a number of changes to the map and to the lists.
*
* WARNING: This class currently only handles the most common cases. A
* UnsupportedOperationException is thrown if an appropriate move
* cannot be generated.
*
*
* @author Luke
*/
public class WorldDiffMove implements Move, MapUpdateMove {
public enum Cause{TrainArrives, Other, YearEnd};
private final Cause cause;
private static final Logger logger = Logger.getLogger(WorldDiffMove.class
.getName());
static class MapDiff implements FreerailsSerializable {
private static final long serialVersionUID = -5935670372745313360L;
final FreerailsSerializable before, after;
final int x, y;
MapDiff(FreerailsSerializable before, FreerailsSerializable after,
ImPoint p) {
this.after = after;
this.before = before;
this.x = p.x;
this.y = p.y;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof MapDiff))
return false;
final MapDiff diff = (MapDiff) o;
if (x != diff.x)
return false;
if (y != diff.y)
return false;
if (!after.equals(diff.after))
return false;
if (!before.equals(diff.before))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = x;
result = 29 * result + y;
result = 29 * result + before.hashCode();
result = 29 * result + after.hashCode();
return result;
}
}
private static final long serialVersionUID = 3905245632406239544L;
public static WorldDiffMove generate(WorldDiffs diffs, Cause cause) {
return new WorldDiffMove(diffs.getUnderlying(), diffs, cause);
}
private final ImList<MapDiff> diffs;
private final CompositeMove listChanges;
private final int x, y, w, h;
public WorldDiffMove(ReadOnlyWorld world, WorldDiffs worldDiffs, Cause cause) throws UnsupportedOperationException {
this.cause = cause;
Iterator<ImPoint> mit = worldDiffs.getMapDiffs();
ArrayList<MapDiff> diffsArrayList = new ArrayList<MapDiff>();
while (mit.hasNext()) {
ImPoint p = mit.next();
FreerailsSerializable oldTile = world.getTile(p.x, p.y);
FreerailsSerializable newTile = worldDiffs.getTile(p.x, p.y);
diffsArrayList.add(new MapDiff(oldTile, newTile, p));
}
diffs = new ImList<MapDiff>(diffsArrayList);
x = 0;
y = 0;
w = world.getMapWidth();
h = world.getMapHeight();
List<Move> tempList = new ArrayList<Move>();
Iterator<ListKey> lit = worldDiffs.getListDiffs();
while (lit.hasNext()) {
ListKey lkey = lit.next();
WorldDiffs.LISTID listId = (LISTID) lkey.getListID();
switch (listId) {
case LISTS: {
int playerId = lkey.getIndex()[0];
FreerailsPrincipal fp = worldDiffs.getPlayer(playerId)
.getPrincipal();
KEY k = KEY.getKey(lkey.getIndex()[1]);
if (lkey.getType() == Element) {
Move m;
int elementId = lkey.getIndex()[2];
// Are we changing an element?
if (elementId < world.size(fp, k)) {
FreerailsSerializable before = world.get(fp, k,
elementId);
FreerailsSerializable after = worldDiffs.get(fp, k,
elementId);
m = new ChangeItemInListMove(k, elementId, before,
after, fp);
} else {
FreerailsSerializable element = worldDiffs.get(fp, k,
elementId);
m = new AddItemToListMove(k, elementId, element, fp);
}
tempList.add(m);
} else {
assert (lkey.getType() == EndPoint);
Integer newSize = (Integer) worldDiffs.getDiff(lkey);
int oldSize = world.size(fp, k);
if (newSize < oldSize) {
throw new UnsupportedOperationException();
}
}
break;
}
case CURRENT_BALANCE:
// Do nothing. The transaction moves should take care of changing
// the values of current balance.
break;
case BANK_ACCOUNTS: {
int playerId = lkey.getIndex()[0];
FreerailsPrincipal fp = worldDiffs.getPlayer(playerId)
.getPrincipal();
if (lkey.getType() == Element) {
Move m;
int elementId = lkey.getIndex()[1];
// Are we changing an element?
if (elementId < world.getNumberOfTransactions(fp)) {
throw new UnsupportedOperationException();
}
Transaction t = worldDiffs.getTransaction(fp, elementId);
m = new AddTransactionMove(fp, t );
tempList.add(m);
} else {
assert (lkey.getType() == EndPoint);
Integer newSize = (Integer) worldDiffs.getDiff(lkey);
int oldSize = world.getNumberOfTransactions(fp);
if (newSize < oldSize) {
throw new UnsupportedOperationException();
}
}
break;
}
case ACTIVITY_LISTS:{
int playerId = lkey.getIndex()[0];
FreerailsPrincipal fp = worldDiffs.getPlayer(playerId)
.getPrincipal();
Object o = worldDiffs.getDiff(lkey);
logger.fine(lkey.toString() + " --> "+ o.toString());
switch (lkey.getIndex().length){
case 1:{
assert (lkey.getType() == EndPoint);
//Do nothing. Adding the activities will increase the
//size of the list.
break;
}
case 2:
assert (lkey.getType() == EndPoint);
//Do nothing. Adding the activities will increase the
//size of the list.
break;
case 3:{
Move m;
//Do we need to add a new active entity?
int entityId = lkey.getIndex()[1];
ActivityAndTime aat = (ActivityAndTime) worldDiffs.getDiff(lkey);
Activity act = aat.act;
int activityID = lkey.getIndex()[2];
if(entityId >= world.getNumberOfActiveEntities(fp) && 0 == activityID){
logger.fine("AddActiveEntityMove: "+act+" entityId="+entityId);
m = new AddActiveEntityMove(act, entityId, fp );
}else{
logger.fine("NextActivityMove: "+act+" entityId="+entityId);
m = new NextActivityMove(act,entityId, fp);
}
tempList.add(m);
break;
}default:
throw new UnsupportedOperationException(listId.toString());
}
break;
}
default:
throw new UnsupportedOperationException(listId.toString());
}
}
listChanges = new CompositeMove(tempList);
}
private void doMove(World world, boolean undo) {
for (int i = 0; i < diffs.size(); i++) {
MapDiff diff = diffs.get(i);
FreerailsSerializable tile = undo ? diff.before : diff.after;
world.setTile(diff.x, diff.y, tile);
}
}
public MoveStatus doMove(World world, FreerailsPrincipal p) {
MoveStatus ms = tryMapChanges(world, false);
if (!ms.ok)
return ms;
ms = listChanges.doMove(world, p);
if (ms.isOk()) {
doMove(world, false);
}
return ms;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof WorldDiffMove))
return false;
final WorldDiffMove mapDiffMove = (WorldDiffMove) o;
if (h != mapDiffMove.h)
return false;
if (w != mapDiffMove.w)
return false;
if (x != mapDiffMove.x)
return false;
if (y != mapDiffMove.y)
return false;
if (!diffs.equals(mapDiffMove.diffs))
return false;
return true;
}
public Rectangle getUpdatedTiles() {
return new Rectangle(x, y, w, h);
}
@Override
public int hashCode() {
int result;
result = diffs.hashCode();
result = 29 * result + x;
result = 29 * result + y;
result = 29 * result + w;
result = 29 * result + h;
return result;
}
public MoveStatus tryDoMove(World world, FreerailsPrincipal p) {
MoveStatus ms = tryMapChanges(world, false);
if (!ms.ok)
return ms;
return ms = listChanges.tryDoMove(world, p);
}
private MoveStatus tryMapChanges(World world, boolean undo) {
for (int i = 0; i < diffs.size(); i++) {
MapDiff diff = diffs.get(i);
FreerailsSerializable actual = world.getTile(diff.x, diff.y);
FreerailsSerializable expected = undo ? diff.after : diff.before;
if (!actual.equals(expected)) {
return MoveStatus.moveFailed("expected =" + expected
+ ", actual = " + actual);
}
}
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World world, FreerailsPrincipal p) {
MoveStatus ms = tryMapChanges(world, true);
if (!ms.ok)
return ms;
return ms = listChanges.tryUndoMove(world, p);
}
public int listDiffs() {
return listChanges.size();
}
public MoveStatus undoMove(World world, FreerailsPrincipal p) {
MoveStatus ms = tryMapChanges(world, true);
if (!ms.ok)
return ms;
ms = listChanges.undoMove(world, p);
if (ms.isOk()) {
doMove(world, true);
}
return ms;
}
public Cause getCause() {
return cause;
}
public CompositeMove getListChanges() {
return listChanges;
}
}
Methods:
MethodJavadoc
doMove
doMove
generate
getCause
getListChanges
getUpdatedTiles
listDiffs
tryDoMove
tryMapChanges
tryUndoMove
undoMove
jfreerails.network.AbstractEchoGameServerTestCase
Javadoc:
/** * Test cases that use EchoGameServer should extend this class. * * @author Luke * */
Source code:
/**
* Test cases that use EchoGameServer should extend this class.
*
* @author Luke
*
*/
public abstract class AbstractEchoGameServerTestCase extends TestCase {
InetConnectionAccepter server;
EchoGameServer echoGameServer;
final String ipAddress = "127.0.0.1";
@Override
protected synchronized void setUp() throws Exception {
echoGameServer = EchoGameServer.startServer();
/*
* There was a problem that occurred intermittently when the unit tests
* were run as a batch. I think it was to do with reusing ports in quick
* succession. Passing 0 as the port allow us to listen on an
* unspecified port whose number we obtain by calling getLocalPort().
* Since making this change, the problem has not occurred.
*/
server = new InetConnectionAccepter(0, echoGameServer);
Thread serverThread = new Thread(server);
serverThread.start();
}
@Override
protected synchronized void tearDown() throws Exception {
server.stop();
}
}
Methods:
MethodJavadoc
setUp
tearDown
jfreerails.network.AbstractInetConnection
Javadoc:
/** * This class has the code that is shared by the client and server versions of * InetConnection. * * @author Luke */
Source code:
/**
* This class has the code that is shared by the client and server versions of
* InetConnection.
*
* @author Luke
*/
public abstract class AbstractInetConnection implements Runnable {
private static final Logger logger = Logger
.getLogger(AbstractInetConnection.class.getName());
private final SynchronizedQueue inbound = new SynchronizedQueue();
private final InetConnection inetConnection;
private final SynchronizedFlag readerThreadStatus = new SynchronizedFlag(
false);
private final SynchronizedFlag status = new SynchronizedFlag(true);
private int timeout = 1000 * 5; // 5 seconds.
public AbstractInetConnection(Socket s) throws IOException {
inetConnection = new InetConnection(s);
open();
}
public AbstractInetConnection(String ip, int port) throws IOException {
inetConnection = new InetConnection(ip, port);
open();
}
public void disconnect() throws IOException {
logger.fine(this + "Initiating shutdown..");
shutdownOutput();
long waitUntil = System.currentTimeMillis() + timeout;
synchronized (readerThreadStatus) {
while (readerThreadStatus.isOpen()) {
long currentTime = System.currentTimeMillis();
if (currentTime >= waitUntil) {
shutDownInput();
throw new IOException(
"Time-out while trying to disconnect.");
}
try {
readerThreadStatus.wait(timeout);
} catch (InterruptedException e) {
// do nothing.
}
}
}
logger.fine(this + "Finished shutdown!! --status="
+ String.valueOf(status.isOpen()));
}
public void flush() throws IOException {
inetConnection.flush();
}
public synchronized boolean isOpen() {
return status.isOpen();
}
public void run() {
try {
while (true) {
FreerailsSerializable fs = inetConnection.receive();
synchronized (inbound) {
inbound.write(fs);
inbound.notifyAll();
}
}
} catch (EOFException e) {
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
logger.fine(this + "Reciprocating shutdown..");
shutDownInput();
readerThreadStatus.close();
}
private synchronized void open() throws IOException {
Thread t = new Thread(this);
t.setName(getThreadName());
inetConnection.open();
t.start();
readerThreadStatus.open();
}
private synchronized void shutDownInput() {
try {
inetConnection.shutdownInput();
logger.fine(this + "Shut down input.");
if (status.isOpen()) {
shutdownOutput();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
private synchronized void shutdownOutput() throws IOException {
if (!status.isOpen()) {
throw new IllegalStateException();
}
status.close();
inetConnection.shutdownOutput();
logger.fine(this + "Shut down output.");
}
abstract String getThreadName();
FreerailsSerializable[] read() throws IOException {
if (status.isOpen()) {
return inbound.read();
}
throw new IOException();
}
void send(FreerailsSerializable object) throws IOException {
inetConnection.send(object);
}
void setTimeOut(int i) {
timeout = i;
}
FreerailsSerializable waitForObject() throws InterruptedException,
IOException {
if (status.isOpen()) {
synchronized (inbound) {
if (inbound.size() > 0) {
return inbound.getFirst();
}
inbound.wait();
if (inbound.size() > 0) {
return inbound.getFirst();
}
throw new IllegalStateException();
}
}
throw new IOException("The connection is close.");
}
}
Methods:
MethodJavadoc
disconnect
flush
getThreadName
isOpen
open
read
run
send
setTimeOut
shutDownInput
shutdownOutput
waitForObject
jfreerails.network.Connection2Client
Javadoc:
/** * Defines the methods the server can use to send messages to the client. * * @author Luke * */
Source code:
/**
* Defines the methods the server can use to send messages to the client.
*
* @author Luke
*
*/
public interface Connection2Client {
/** Returns true if this connection is open. */
boolean isOpen();
/**
* Returns an array containing all the objects read from the client since
* the last time this method or waitForObjectFromClient() was called, if no
* objects have been received, it returns an empty array rather than
* blocking.
*/
FreerailsSerializable[] readFromClient() throws IOException;
/**
* Returns the next object read from the client, blocking if non is
* available.
*/
FreerailsSerializable waitForObjectFromClient() throws IOException,
InterruptedException;
/** Sends the specified object to the client. */
void writeToClient(FreerailsSerializable object) throws IOException;
/** Flush the underlying stream. */
void flush() throws IOException;
/**
* Disconnect from the client. When this method returns, calling isOpen() on
* this object returns false <b>and</b> calling isOpen() on the
* corresponding Connection2Server held by the client also returns false.
*
* @throws IOException
*/
void disconnect() throws IOException;
}
Methods:
MethodJavadoc
disconnect/**
flush/** Flush the underlying stream. */
isOpen/** Returns true if this connection is open. */
readFromClient/**
waitForObjectFromClient/**
writeToClient/** Sends the specified object to the client. */
jfreerails.network.Connection2Server
Javadoc:
/** * Defines the methods a client can use to send messages to the server. * * @author Luke * */
Source code:
/**
* Defines the methods a client can use to send messages to the server.
*
* @author Luke
*
*/
public interface Connection2Server {
/** Returns true if this connection is open. */
boolean isOpen();
/**
* Returns an array containing all the objects read from the server since
* the last time this method or waitForObjectFromServer() was called, if no
* objects have been received, it returns an empty array rather than
* blocking.
*/
FreerailsSerializable[] readFromServer() throws IOException;
/**
* Returns the next object read from the server, blocking if non is
* available.
*/
FreerailsSerializable waitForObjectFromServer() throws IOException,
InterruptedException;
/** Sends the specified object to the server. */
void writeToServer(FreerailsSerializable object) throws IOException;
/**
* Disconnect from the server. When this method returns, calling isOpen() on
* this object returns false <b>and</b> calling isOpen() on the
* corresponding Connection2Client held by the server also returns false.
*
* @throws IOException
*/
void disconnect() throws IOException;
/** Flush the underlying stream. */
void flush() throws IOException;
String getServerDetails();
}
Methods:
MethodJavadoc
disconnect/**
flush/** Flush the underlying stream. */
getServerDetails
isOpen/** Returns true if this connection is open. */
readFromServer/**
waitForObjectFromServer/**
writeToServer/** Sends the specified object to the server. */
jfreerails.network.EchoGameServer
Javadoc:
/** * Implementation of GameServer that simply echoes whatever clients send it. * * @author Luke * */
Source code:
/**
* Implementation of GameServer that simply echoes whatever clients send it.
*
* @author Luke
*
*/
public class EchoGameServer implements GameServer, Runnable {
private static final Logger logger = Logger.getLogger(EchoGameServer.class
.getName());
private final Vector<Connection2Client> connections = new Vector<Connection2Client>();
private final SynchronizedFlag status = new SynchronizedFlag(false);
private final LinkedList<FreerailsSerializable> messages2send = new LinkedList<FreerailsSerializable>();
private EchoGameServer() {
}
/**
* Creates an EchoGameServer, starts it in a new Thread, and waits for its
* status to change to isOpen before returning.
*/
public static EchoGameServer startServer() {
EchoGameServer server = new EchoGameServer();
Thread t = new Thread(server);
t.start();
try {
/* Wait for the server to start before returning. */
synchronized (server.status) {
server.status.wait();
}
return server;
} catch (InterruptedException e) {
e.printStackTrace();
throw new IllegalStateException();
}
}
public synchronized void addConnection(Connection2Client connection) {
if (null == connection) {
throw new NullPointerException();
}
if (!status.isOpen()) {
throw new IllegalArgumentException();
}
connections.add(connection);
}
public synchronized int countOpenConnections() {
Iterator<Connection2Client> it = connections.iterator();
while (it.hasNext()) {
Connection2Client connection = it.next();
if (!connection.isOpen()) {
it.remove();
}
}
return connections.size();
}
public synchronized void stop() {
status.close();
for (int i = 0; i < connections.size(); i++) {
AbstractInetConnection connection = (AbstractInetConnection) connections
.get(i);
if (connection.isOpen()) {
try {
connection.setTimeOut(0);
connection.disconnect();
} catch (Exception e) {
// Do nothing.
}
}
}
}
public void run() {
status.open();
while (status.isOpen()) {
update();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// do nothing.
}
}
}
synchronized void sendMessage(FreerailsSerializable m) {
/* Send messages. */
for (int i = 0; i < connections.size(); i++) {
Connection2Client connection = connections.get(i);
try {
connection.writeToClient(m);
connection.flush();
logger.fine("Sent ok: " + m);
} catch (IOException e) {
try {
if (connection.isOpen()) {
connection.disconnect();
}
} catch (IOException e1) {
// hope this doesn't happen.
e1.printStackTrace();
}
}
}
}
public void update() {
synchronized (this) {
/* Read messages. */
for (int i = 0; i < connections.size(); i++) {
Connection2Client connection = connections.get(i);
try {
FreerailsSerializable[] messages = connection
.readFromClient();
for (int j = 0; j < messages.length; j++) {
messages2send.add(messages[j]);
}
} catch (IOException e) {
try {
if (connection.isOpen()) {
connection.disconnect();
}
} catch (IOException e1) {
//
e1.printStackTrace();
}
}
}
/* Send messages. */
Iterator<FreerailsSerializable> messagesIterator = messages2send
.iterator();
while (messagesIterator.hasNext()) {
FreerailsSerializable message = messagesIterator.next();
sendMessage(message);
}
}
}
}
Methods:
MethodJavadoc
addConnection
countOpenConnections
run
sendMessage
startServer/**
stop
update
jfreerails.network.GameServer
Javadoc:
/** * Defines a server that can accept connections to clients. * * @author Luke * */
Source code:
/**
* Defines a server that can accept connections to clients.
*
* @author Luke
*
*/
public interface GameServer extends GameModel {
void addConnection(Connection2Client connection);
int countOpenConnections();
void stop();
}
Methods:
MethodJavadoc
addConnection
countOpenConnections
stop
jfreerails.network.InetConnection
Javadoc:
/** * Provides methods send objects over the Internet, and connect and disconnect * gracefully. * * @author Luke * */
Source code:
/**
* Provides methods send objects over the Internet, and connect and disconnect
* gracefully.
*
* @author Luke
*
*/
public class InetConnection {
private final Socket socket;
// Note compression commented out since it was causing junit tests to fail.
// Not
// sure why. LL
// private DeflaterOutputStream deflaterOutputStream;
// private InflaterInputStream inflaterInputStream;
private ObjectOutputStream objectOutputStream;
private ObjectInputStream objectInputStream;
private static final String CONNECTION_OPEN = "CONNECTION_OPEN";
InetConnection(Socket acceptedConnection) throws IOException {
socket = acceptedConnection;
}
InetConnection(String s, int port) throws IOException {
this(new Socket(s, port));
}
/**
* Sets up the input and output streams, then sends the String
* "CONNECTION_OPEN" and attempts to read the same String back.
*/
synchronized void open() throws IOException {
OutputStream outputStream = socket.getOutputStream();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
outputStream);
// deflaterOutputStream = new DeflaterOutputStream(outputStream);
// objectOutputStream = new ObjectOutputStream(deflaterOutputStream);
objectOutputStream = new ObjectOutputStream(bufferedOutputStream);
objectOutputStream.writeObject(CONNECTION_OPEN);
objectOutputStream.flush();
InputStream inputStream = socket.getInputStream();
// inflaterInputStream = new InflaterInputStream(inputStream);
// objectInputStream = new ObjectInputStream(inflaterInputStream);
objectInputStream = new ObjectInputStream(inputStream);
try {
String s = (String) objectInputStream.readObject();
if (!s.equals(CONNECTION_OPEN)) {
throw new IllegalStateException(s);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IOException(e.getMessage());
}
}
synchronized void send(FreerailsSerializable object) throws IOException {
objectOutputStream.writeObject(object);
flush();
}
FreerailsSerializable receive() throws IOException, ClassNotFoundException {
Object object = objectInputStream.readObject();
return (FreerailsSerializable) object;
}
synchronized boolean isOpen() {
boolean isClosed = socket.isClosed();
return !isClosed;
}
synchronized void flush() throws IOException {
objectOutputStream.flush();
// deflaterOutputStream.flush();
// deflaterOutputStream.finish();
// deflaterOutputStream.flush();
}
synchronized void shutdownOutput() throws IOException {
socket.shutdownOutput();
if (socket.isInputShutdown() && socket.isOutputShutdown()) {
socket.close();
}
}
synchronized void shutdownInput() throws IOException {
socket.shutdownInput();
if (socket.isInputShutdown() && socket.isOutputShutdown()) {
socket.close();
}
}
}
Methods:
MethodJavadoc
flush
isOpen
open/**
receive
send
shutdownInput
shutdownOutput
jfreerails.network.InetConnection2Client
Javadoc:
/** * Lets the server send messages to a client over the Internet. * * @author Luke * */
Source code:
/**
* Lets the server send messages to a client over the Internet.
*
* @author Luke
*
*/
public class InetConnection2Client extends AbstractInetConnection implements
Connection2Client {
public InetConnection2Client(Socket s) throws IOException {
super(s);
}
public FreerailsSerializable[] readFromClient() throws IOException {
return read();
}
public FreerailsSerializable waitForObjectFromClient() throws IOException,
InterruptedException {
return waitForObject();
}
public void writeToClient(FreerailsSerializable object) throws IOException {
send(object);
}
@Override
String getThreadName() {
return "InetConnection2Client";
}
}
Methods:
MethodJavadoc
getThreadName
readFromClient
waitForObjectFromClient
writeToClient
jfreerails.network.InetConnection2Server
Javadoc:
/** * Lets a client send messages to the server over the Internet. * * @author Luke * */
Source code:
/**
* Lets a client send messages to the server over the Internet.
*
* @author Luke
*
*/
public class InetConnection2Server extends AbstractInetConnection implements
Connection2Server {
final String serverDetails;
public InetConnection2Server(String ip, int port) throws IOException {
super(ip, port);
serverDetails = "server at " + ip + ":" + port;
}
public FreerailsSerializable[] readFromServer() throws IOException {
return read();
}
public FreerailsSerializable waitForObjectFromServer() throws IOException,
InterruptedException {
return waitForObject();
}
public void writeToServer(FreerailsSerializable object) throws IOException {
send(object);
}
@Override
String getThreadName() {
return "InetConnection2Server";
}
public String getServerDetails() {
return serverDetails;
}
}
Methods:
MethodJavadoc
getServerDetails
getThreadName
readFromServer
waitForObjectFromServer
writeToServer
jfreerails.network.InetConnectionAccepter
Javadoc:
/** * When this class is run in a thread it accepts new connections to its Server * Socket and adds them to the NewGameServer that was passed to its constructor. * * @author Luke */
Source code:
/**
* When this class is run in a thread it accepts new connections to its Server
* Socket and adds them to the NewGameServer that was passed to its constructor.
*
* @author Luke
*/
public class InetConnectionAccepter implements Runnable {
private static final Logger logger = Logger
.getLogger(InetConnectionAccepter.class.getName());
public static void main(String[] args) {
try {
GameServer echoGameServer = EchoGameServer.startServer();
InetConnectionAccepter accepter = new InetConnectionAccepter(6666,
echoGameServer);
Thread t = new Thread(accepter);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
private final GameServer gameServer;
private final SynchronizedFlag keepRunning = new SynchronizedFlag(true);
private final ServerSocket serverSocket;
public InetConnectionAccepter(int port, GameServer gameServer)
throws IOException {
if (null == gameServer)
throw new NullPointerException();
this.gameServer = gameServer;
serverSocket = new ServerSocket(port);
}
public void run() {
Thread.currentThread().setName(
"InetConnectionAccepter, port " + serverSocket.getLocalPort());
try {
logger.fine("Accepting connections on port "
+ serverSocket.getLocalPort());
while (isKeepRunning()) {
Socket socket = serverSocket.accept();
logger.fine("Incoming connection from "
+ socket.getRemoteSocketAddress());
synchronized (this) {
synchronized (gameServer) {
InetConnection2Client connection = new InetConnection2Client(
socket);
gameServer.addConnection(connection);
}
}
}
} catch (IOException e) {
try {
stop();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
public synchronized void stop() throws IOException {
this.keepRunning.close();
serverSocket.close();
// Commented out since it causes exceptions to be thrown, fixes bug
// 979831
// gameServer.stop();
}
private boolean isKeepRunning() {
return keepRunning.isOpen();
}
public int getLocalPort() {
return serverSocket.getLocalPort();
}
}
Methods:
MethodJavadoc
getLocalPort
isKeepRunning
main
run
stop
jfreerails.network.LocalConnection
Javadoc:
/** * A connection between the a client and server in the same JVM. * * @author Luke * */
Source code:
/**
* A connection between the a client and server in the same JVM.
*
* @author Luke
*
*/
public class LocalConnection implements Connection2Client, Connection2Server {
public static final String SERVER_IN_SAME_JVM = "server in same JVM";
private final SynchronizedQueue fromServer = new SynchronizedQueue();
private final SynchronizedQueue fromClient = new SynchronizedQueue();
private final SynchronizedFlag status = new SynchronizedFlag(true);
public LocalConnection() {
}
public FreerailsSerializable[] readFromClient() throws IOException {
if (status.isOpen()) {
return fromClient.read();
}
throw new IOException();
}
public FreerailsSerializable waitForObjectFromClient() throws IOException,
InterruptedException {
synchronized (fromClient) {
if (fromClient.size() == 0) {
fromClient.wait();
}
if (status.isOpen()) {
return fromClient.getFirst();
}
throw new IOException();
}
}
public void writeToClient(FreerailsSerializable object) throws IOException {
if (status.isOpen()) {
synchronized (fromServer) {
fromServer.write(object);
fromServer.notifyAll();
}
} else {
throw new IOException();
}
}
public FreerailsSerializable[] readFromServer() throws IOException {
if (status.isOpen()) {
return fromServer.read();
}
throw new IOException();
}
public FreerailsSerializable waitForObjectFromServer() throws IOException,
InterruptedException {
if (status.isOpen()) {
synchronized (fromServer) {
if (fromServer.size() == 0) {
fromServer.wait();
}
return fromServer.getFirst();
}
}
throw new IOException();
}
public void writeToServer(FreerailsSerializable object) throws IOException {
if (status.isOpen()) {
synchronized (fromClient) {
fromClient.write(object);
fromClient.notifyAll();
}
} else {
throw new IOException();
}
}
public boolean isOpen() {
return status.isOpen();
}
public void flush() {
// No need to do anything.
}
public synchronized void disconnect() {
status.close();
}
public String getServerDetails() {
return SERVER_IN_SAME_JVM;
}
}
Methods:
MethodJavadoc
disconnect
flush
getServerDetails
isOpen
readFromClient
readFromServer
waitForObjectFromClient
waitForObjectFromServer
writeToClient
writeToServer
jfreerails.network.SynchronizedFlag
Javadoc:
/** * Synchronized flag - used to tell threads whether they should keep going. * Note, thought about using volatile keyword but wasn't sure if it is * implemented on all JVMs * * @author Luke */
Source code:
/**
* Synchronized flag - used to tell threads whether they should keep going.
* Note, thought about using volatile keyword but wasn't sure if it is
* implemented on all JVMs
*
* @author Luke
*/
public class SynchronizedFlag {
public SynchronizedFlag(boolean b) {
this.isOpen = b;
}
private boolean isOpen = true;
public synchronized boolean isOpen() {
return isOpen;
}
public synchronized void close() {
this.isOpen = false;
notifyAll();
}
public synchronized void open() {
this.isOpen = true;
notifyAll();
}
}
Methods:
MethodJavadoc
close
isOpen
open
jfreerails.network.SynchronizedQueue
Javadoc:
/** * Intended to let objects be safely passed between threads. * * @author Luke * */
Source code:
/**
* Intended to let objects be safely passed between threads.
*
* @author Luke
*
*/
public class SynchronizedQueue {
private final LinkedList<FreerailsSerializable> queue = new LinkedList<FreerailsSerializable>();
public synchronized void write(FreerailsSerializable f) {
queue.add(f);
}
public synchronized FreerailsSerializable[] read() {
int length = queue.size();
FreerailsSerializable[] read = new FreerailsSerializable[length];
for (int i = 0; i < length; i++) {
read[i] = queue.removeFirst();
}
return read;
}
public synchronized int size() {
return queue.size();
}
public synchronized FreerailsSerializable getFirst() {
return queue.removeFirst();
}
}
Methods:
MethodJavadoc
getFirst
read
size
write
jfreerails.network.specifics.AbstractFreerailsServerTestCase
Javadoc:
/** * Test cases that use FreerailsGameServer <b>and</b> connect over the Internet * should extend this class . * * @author Luke * */
Source code:
/**
* Test cases that use FreerailsGameServer <b>and</b> connect over the Internet
* should extend this class .
*
* @author Luke
*
*/
public abstract class AbstractFreerailsServerTestCase extends TestCase {
private InetConnectionAccepter connectionAccepter;
protected FreerailsGameServer server;
private final String ipAddress = "127.0.0.1";
@Override
protected synchronized void setUp() throws Exception {
server = FreerailsGameServer
.startServer(new SavedGamesManager4UnitTests());
connectionAccepter = new InetConnectionAccepter(0, server);
Thread serverThread = new Thread(connectionAccepter);
serverThread.start();
}
@Override
protected synchronized void tearDown() throws Exception {
connectionAccepter.stop();
}
protected int getPort() {
return connectionAccepter.getLocalPort();
}
protected String getIpAddress() {
return ipAddress;
}
}
Methods:
MethodJavadoc
getIpAddress
getPort
setUp
tearDown
jfreerails.network.specifics.FreerailsClient
Javadoc:
/** * A client for FreerailsGameServer. * * @author Luke * */
Source code:
/**
* A client for FreerailsGameServer.
*
* @author Luke
*
*/
public class FreerailsClient implements ClientControlInterface, GameModel,
UntriedMoveReceiver, ServerCommandReceiver {
private static final Logger logger = Logger.getLogger(FreerailsClient.class
.getName());
protected Connection2Server connection2Server;
private final HashMap<String, Serializable> properties = new HashMap<String, Serializable>();
private final MoveChainFork moveFork;
private World world;
private MovePrecommitter committer;
public FreerailsClient() {
moveFork = new MoveChainFork();
}
public final MoveChainFork getMoveFork() {
return moveFork;
}
/**
* Connects this client to a remote server.
*/
public final LogOnResponse connect(String address, int port,
String username, String password) {
logger.fine("Connect to remote server. " + address + ":" + port);
try {
connection2Server = new InetConnection2Server(address, port);
} catch (IOException e) {
return LogOnResponse.rejected(e.getMessage());
}
try {
LogOnRequest request = new LogOnRequest(username, password);
connection2Server.writeToServer(request);
connection2Server.flush();
LogOnResponse response = (LogOnResponse) connection2Server
.waitForObjectFromServer();
return response;
} catch (Exception e) {
try {
connection2Server.disconnect();
} catch (IOException e1) {
e1.printStackTrace();
}
return LogOnResponse.rejected(e.getMessage());
}
}
/**
* Connects this client to a local server.
*/
public final LogOnResponse connect(GameServer server, String username,
String password) {
try {
LogOnRequest request = new LogOnRequest(username, password);
connection2Server = new LocalConnection();
connection2Server.writeToServer(request);
server.addConnection((LocalConnection) connection2Server);
LogOnResponse response = (LogOnResponse) connection2Server
.waitForObjectFromServer();
return response;
} catch (Exception e) {
try {
connection2Server.disconnect();
} catch (IOException e1) {
e1.printStackTrace();
}
return LogOnResponse.rejected(e.getMessage());
}
}
/**
* Disconnect the client from the server.
*/
public final void disconnect() {
try {
connection2Server.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
public final void setGameModel(FreerailsMutableSerializable o) {
world = (World) o;
committer = new MovePrecommitter(world);
newWorld(world);
}
/**
* Subclasses should override this method if they need to respond the the
* world being changed.
*/
protected void newWorld(World w) {
}
public void setProperty(ClientProperty propertyName, Serializable value) {
properties.put(propertyName.name(), value);
}
public final Serializable getProperty(ClientProperty propertyName) {
return properties.get(propertyName.name());
}
public final void resetProperties(HashMap newProperties) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
final FreerailsSerializable read() {
try {
return this.connection2Server.waitForObjectFromServer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
throw new IllegalStateException();
}
final void write(FreerailsSerializable fs) {
try {
connection2Server.writeToServer(fs);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException();
}
}
/** Reads and deals with all outstanding messages from the server. */
final public void update() {
try {
FreerailsSerializable[] messages = connection2Server
.readFromServer();
for (int i = 0; i < messages.length; i++) {
FreerailsSerializable message = messages[i];
processMessage(message);
}
connection2Server.flush();
clientUpdates();
} catch (IOException e) {
ReportBugTextGenerator.unexpectedException(e);
}
}
/**
* Empty method called by update(), subclasses should override this method
* instead of overriding update().
*
*/
protected void clientUpdates() {
}
/** Processes a message received from the server. */
final void processMessage(FreerailsSerializable message) throws IOException {
if (message instanceof Message2Client) {
Message2Client request = (Message2Client) message;
MessageStatus status = request.execute(this);
logger.fine(request.toString());
connection2Server.writeToServer(status);
} else if (message instanceof Move) {
Move m = (Move) message;
committer.fromServer(m);
moveFork.processMove(m);
} else if (message instanceof MoveStatus) {
MoveStatus ms = (MoveStatus) message;
committer.fromServer(ms);
} else if (message instanceof PreMove) {
PreMove pm = (PreMove) message;
Move m = committer.fromServer(pm);
moveFork.processMove(m);
} else if (message instanceof PreMoveStatus) {
PreMoveStatus pms = (PreMoveStatus) message;
committer.fromServer(pms);
} else {
logger.fine(message.toString());
}
}
final public World getWorld() {
return world;
}
/** Sends move to the server. */
final public void processMove(Move move) {
committer.toServer(move);
moveFork.processMove(move);
write(move);
}
/** Tests a move before sending it to the server. */
final public MoveStatus tryDoMove(Move move) {
return move.tryDoMove(world, Player.AUTHORITATIVE);
}
public void sendCommand(Message2Server c) {
write(c);
}
public void processPreMove(PreMove pm) {
Move m = committer.toServer(pm);
moveFork.processMove(m);
write(pm);
}
protected long getLastTickTime(){
return moveFork.getLastTickTime();
}
}
Methods:
MethodJavadoc
clientUpdates/**
connect/**
connect/**
disconnect/**
getLastTickTime
getMoveFork
getProperty
getWorld
newWorld/**
processMessage/** Processes a message received from the server. */
processMove/** Sends move to the server. */
processPreMove
read
resetProperties
sendCommand
setGameModel
setProperty
tryDoMove/** Tests a move before sending it to the server. */
update/** Reads and deals with all outstanding messages from the server. */
write
jfreerails.network.specifics.FreerailsGameServer
Javadoc:
/** * When executed by a thread, this class does the following: reads and executes * moves and commands received from connected clients; sends moves and commands * to connected clients. * * @see InetConnectionAccepter * @see Connection2Client * * @author Luke * */
Source code:
/**
* When executed by a thread, this class does the following: reads and executes
* moves and commands received from connected clients; sends moves and commands
* to connected clients.
*
* @see InetConnectionAccepter
* @see Connection2Client
*
* @author Luke
*
*/
public class FreerailsGameServer implements ServerControlInterface, GameServer,
Runnable {
/** Used as a property name for property change events. */
public static final String CONNECTED_PLAYERS = "CONNECTED_PLAYERS";
private static final Logger logger = Logger
.getLogger(FreerailsGameServer.class.getName());
public static FreerailsGameServer startServer(SavedGamesManager gamesManager) {
FreerailsGameServer server = new FreerailsGameServer(gamesManager);
Thread t = new Thread(server);
t.start();
try {
/* Wait for the server to start before returning. */
synchronized (server.status) {
server.status.wait();
}
return server;
} catch (InterruptedException e) {
e.printStackTrace();
throw new IllegalStateException();
}
}
private final HashMap<NameAndPassword, Connection2Client> acceptedConnections = new HashMap<NameAndPassword, Connection2Client>();
private int commandID = 0;
/**
* ID of the last SetWorldMessage2Client sent out. Used to keep track of
* which clients have updated their world object to the current version.
*/
private int confirmationID = Integer.MIN_VALUE; /*
* Don't default 0 to avoid
* mistaken confirmations.
*/
/**
* The players who have confirmed that they have received the last copy of
* the world object sent.
*/
private HashSet<NameAndPassword> confirmedPlayers = new HashSet<NameAndPassword>();
/* Contains the user names of the players who are currently logged on. */
private HashSet<NameAndPassword> currentlyLoggedOn = new HashSet<NameAndPassword>();
private boolean newPlayersAllowed = true;
private ArrayList<NameAndPassword> players = new ArrayList<NameAndPassword>();
private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
this);
private final SavedGamesManager savedGamesManager;
private ServerGameModel serverGameModel = new SimpleServerGameModel();
private final SynchronizedFlag status = new SynchronizedFlag(false);
public FreerailsGameServer(SavedGamesManager gamesManager) {
this.savedGamesManager = gamesManager;
}
public synchronized void addConnection(Connection2Client connection) {
String[] before = getPlayerNames();
logger.fine("Adding connection..");
logger.fine("Waiting for login details..");
try {
LogOnRequest request = (LogOnRequest) connection
.waitForObjectFromClient();
logger.fine("Trying to login player: " + request.getUsername());
LogOnResponse response = this.logon(request);
connection.writeToClient(response);
connection.flush();
NameAndPassword p = new NameAndPassword(request.getUsername(),
request.getPassword());
if (response.isSuccessful()) {
logger.fine("Login successful");
synchronized (acceptedConnections) {
acceptedConnections.put(p, connection);
}
/* Just send to the new client. */
Message2Client setMaps = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.MAPS_AVAILABLE,
new ImStringList(savedGamesManager.getNewMapNames()));
ImStringList savedGameNames = new ImStringList(
savedGamesManager.getSaveGameNames());
Message2Client setSaveGames = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.SAVED_GAMES, savedGameNames);
connection.writeToClient(setMaps);
connection.writeToClient(setSaveGames);
// no need to flush since it is done in
// sendListOfConnectedPlayers2Clients()
/*
* If there is a game in progress, we need to send the client a
* copy of the world object.
*/
if (null != serverGameModel && null != getWorld()) {
SetWorldMessage2Client command = new SetWorldMessage2Client(
confirmationID, getWorld());
connection.writeToClient(command);
}
/* Send to all clients. */
sendListOfConnectedPlayers2Clients();
String[] after = getPlayerNames();
propertyChangeSupport.firePropertyChange("CONNECTED_PLAYERS",
before, after);
} else {
connection.disconnect();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
public synchronized int countOpenConnections() {
Iterator<NameAndPassword> it = acceptedConnections.keySet().iterator();
int numConnections = 0;
while (it.hasNext()) {
Connection2Client connection = acceptedConnections.get(it.next());
if (connection.isOpen()) {
numConnections++;
}
}
return numConnections;
}
World getCopyOfWorld() {
return this.getWorld().defensiveCopy();
}
private int getNextClientCommandId() {
return commandID++;
}
public String[] getPlayerNames() {
String[] playerNames = new String[players.size()];
for (int i = 0; i < players.size(); i++) {
playerNames[i] = players.get(i).username;
}
return playerNames;
}
private World getWorld() {
return serverGameModel.getWorld();
}
boolean isConfirmed(int player) {
logger.fine("confirmedPlayers.size()=" + confirmedPlayers.size());
boolean isConfirmed = confirmedPlayers.contains(players.get(player));
return isConfirmed;
}
public boolean isNewPlayersAllowed() {
return newPlayersAllowed;
}
private boolean isPlayer(String username) {
for (NameAndPassword p : players) {
if (p.username.equals(username))
return true;
}
return false;
}
public void loadgame(String saveGameName) throws IOException {
logger.info("load game " + saveGameName);
newPlayersAllowed = false;
confirmedPlayers.clear();
ServerGameModel loadedGame;
loadedGame = (ServerGameModel) savedGamesManager.loadGame(saveGameName);
String[] passwords = loadedGame.getPasswords();
World w = loadedGame.getWorld();
assert passwords.length == w.getNumberOfPlayers();
ArrayList<NameAndPassword> newPlayers = new ArrayList<NameAndPassword>();
for (int i = 0; i < passwords.length; i++) {
Player player = w.getPlayer(i);
NameAndPassword nap = new NameAndPassword(player.getName(),
passwords[i]);
newPlayers.add(nap);
}
/*
* Remove any currently logged on players who are not participants in
* the game we are loading.
*/
for (NameAndPassword nap : players) {
if (!newPlayers.contains(nap) && currentlyLoggedOn.contains(nap)) {
removeConnection(nap);
}
}
players = newPlayers;
setServerGameModel(loadedGame);
sendWorldUpdatedCommand();
}
public void logoff(int player) {
NameAndPassword np = players.get(player);
currentlyLoggedOn.remove(np);
}
public LogOnResponse logon(LogOnRequest lor) {
NameAndPassword p = new NameAndPassword(lor.getUsername(), lor
.getPassword());
boolean isReturningPlayer = isPlayer(lor.getUsername());
if (!this.newPlayersAllowed && !isReturningPlayer) {
return LogOnResponse.rejected("New logins not allowed.");
}
if (currentlyLoggedOn.contains(p)) {
return LogOnResponse.rejected("Already logged on.");
}
if (isReturningPlayer) {
if (!players.contains(p)) {
return LogOnResponse.rejected("Incorrect password.");
}
} else {
players.add(p);
}
currentlyLoggedOn.add(p);
return LogOnResponse.accepted(players.indexOf(p));
}
public void newGame(String mapName, int numAI) {
for (int i = 0; i < numAI; ++i) {
NameAndPassword aiPlayer = new NameAndPassword("AI" + i, null);
players.add(aiPlayer);
}
this.newGame(mapName);
}
public void newGame(String mapName) {
newPlayersAllowed = false;
confirmedPlayers.clear();
try {
World world = (World) savedGamesManager.newMap(mapName);
String[] passwords = new String[players.size()];
/* Add players to world. */
for (int i = 0; i < players.size(); i++) {
String name = players.get(i).username;
Player p = new Player(name, i);
Move addPlayerMove = AddPlayerMove.generateMove(world, p);
MoveStatus ms = addPlayerMove.doMove(world, Player.AUTHORITATIVE);
if(!ms.ok) throw new IllegalStateException();
passwords[i] = players.get(i).password;
}
serverGameModel.setWorld(world, passwords);
setServerGameModel(serverGameModel);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendWorldUpdatedCommand();
logger.fine("newGame");
}
private void removeConnection(NameAndPassword p) throws IOException {
String[] before = getPlayerNames();
Connection2Client connection = acceptedConnections.get(p);
/*
* Fix for bug 1047439 Shutting down remote client crashes server We get
* an IllegalStateException if we try to disconnect a connection that is
* not open.
*/
if (connection.isOpen()) {
connection.disconnect();
}
this.currentlyLoggedOn.remove(p);
String[] after = getPlayerNames();
propertyChangeSupport.firePropertyChange("CONNECTED_PLAYERS", before,
after);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
public void run() {
status.open();
status.close();
}
public void savegame(String saveGameName) {
logger.info("save game as " + saveGameName);
try {
savedGamesManager.saveGame(serverGameModel, saveGameName);
String[] saves = savedGamesManager.getSaveGameNames();
Message2Client request = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.SAVED_GAMES, new ImStringList(
saves));
send2All(request);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void send2All(FreerailsSerializable message) {
send2AllExcept(null, message);
}
/** Sends the specified message to all connections except the specified one. */
private void send2AllExcept(Connection2Client dontSend2,
FreerailsSerializable message) {
Iterator<NameAndPassword> it = acceptedConnections.keySet().iterator();
while (it.hasNext()) {
NameAndPassword p = it.next();
Connection2Client connection = acceptedConnections.get(p);
if (dontSend2 != connection) {
try {
connection.writeToClient(message);
connection.flush();
} catch (Exception e) {
if (connection.isOpen()) {
e.printStackTrace();
try {
removeConnection(p);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
}
private void sendListOfConnectedPlayers2Clients() throws IOException {
/* Send the client the list of players. */
String[] playerNames = getPlayerNames();
Message2Client request = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.CONNECTED_CLIENTS, new ImStringList(
playerNames));
send2All(request);
}
private void sendWorldUpdatedCommand() {
/* Send the world to the clients. */
confirmationID = getNextClientCommandId();
SetWorldMessage2Client command = new SetWorldMessage2Client(
confirmationID, getWorld());
send2All(command);
}
public void setNewPlayersAllowed(boolean newPlayersAllowed) {
this.newPlayersAllowed = newPlayersAllowed;
}
public void setServerGameModel(ServerGameModel serverGameModel) {
this.serverGameModel = serverGameModel;
MoveReceiver moveExecutor = new MoveReceiver() {
public void processMove(Move move) {
MoveStatus ms = move.doMove(getWorld(), Player.AUTHORITATIVE);
if (ms.ok) {
send2All(move);
} else {
logger.warning(ms.message);
}
}
};
serverGameModel.init(moveExecutor);
}
public void stop() {
// TODO Auto-generated method stub
}
public void stopGame() {
logger.info("Stop game.");
}
/**
* Updates the game model, then reads and deals with the outstanding
* messages from each of the connected clients. This method is synchronized
* to prevent moves being sent out while addConnection(.) is executing.
*/
public synchronized void update() {
if (null != serverGameModel) {
serverGameModel.update();
}
try {
Iterator<NameAndPassword> it = acceptedConnections.keySet()
.iterator();
while (it.hasNext()) {
NameAndPassword player = it.next();
Connection2Client connection = acceptedConnections.get(player);
if (connection.isOpen()) {
FreerailsSerializable[] messages = connection
.readFromClient();
for (int i = 0; i < messages.length; i++) {
if (messages[i] instanceof Message2Server) {
Message2Server message2 = (Message2Server) messages[i];
MessageStatus cStatus = message2.execute(this);
logger.fine(message2.toString());
connection.writeToClient(cStatus);
} else if (messages[i] instanceof MessageStatus) {
MessageStatus messageStatus = (MessageStatus) messages[i];
if (messageStatus.getId() == this.confirmationID) {
/*
* The client is confirming that they have
* updated their world object to the current
* version.
*/
this.confirmedPlayers.add(player);
logger.fine("Confirmed player " + player);
}
logger.fine(messages[i].toString());
} else if (messages[i] instanceof Move
|| messages[i] instanceof PreMove) {
Player player2 = getWorld().getPlayer(
players.indexOf(player));
FreerailsPrincipal principal = player2
.getPrincipal();
Move move;
boolean isMove = messages[i] instanceof Move;
if (isMove) {
move = (Move) messages[i];
} else {
PreMove pm = (PreMove) messages[i];
move = pm.generateMove(getWorld());
}
MoveStatus mStatus = move.tryDoMove(
this.getWorld(), principal);
if (mStatus.isOk()) {
move.doMove(getWorld(), principal);
/*
* We don't send the move to the client that
* submitted it.
*/
send2AllExcept(connection, move);
}
if (isMove) {
connection.writeToClient(mStatus);
} else {
connection.writeToClient(PreMoveStatus
.fromMoveStatus(mStatus));
}
} else {
logger.fine(messages[i].toString());
}
}
connection.flush();
} else {
/* Remove connection. */
this.removeConnection(player);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void refreshSavedGames() {
Message2Client setMaps = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.MAPS_AVAILABLE,
new ImStringList(savedGamesManager.getNewMapNames()));
ImStringList savedGameNames = new ImStringList(
savedGamesManager.getSaveGameNames());
Message2Client setSaveGames = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.SAVED_GAMES, savedGameNames);
send2All(setMaps);
send2All(setSaveGames);
}
}
Methods:
MethodJavadoc
addConnection
addPropertyChangeListener
countOpenConnections
getCopyOfWorld
getNextClientCommandId
getPlayerNames
getWorld
isConfirmed
isNewPlayersAllowed
isPlayer
loadgame
logoff/**
logon
newGame
newGame
refreshSavedGames
removeConnection
removePropertyChangeListener
run
savegame
send2All
send2AllExcept/** Sends the specified message to all connections except the specified one. */
sendListOfConnectedPlayers2Clients
sendWorldUpdatedCommand
setNewPlayersAllowed
setServerGameModel
startServer
stop
stopGame
update/**
jfreerails.network.specifics.LoadGameMessage2Server
Javadoc:
/** * Request to load a game. * * @author Luke * */
Source code:
/**
* Request to load a game.
*
* @author Luke
*
*/
public class LoadGameMessage2Server implements Message2Server {
private static final long serialVersionUID = 3256726186552930869L;
private final int id;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof LoadGameMessage2Server))
return false;
final LoadGameMessage2Server loadGameMessage2Server = (LoadGameMessage2Server) o;
if (id != loadGameMessage2Server.id)
return false;
if (!filename.equals(loadGameMessage2Server.filename))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + filename.hashCode();
return result;
}
private final String filename;
public LoadGameMessage2Server(int id, String s) {
this.id = id;
this.filename = s;
}
public int getID() {
return id;
}
public MessageStatus execute(ServerControlInterface server) {
try {
server.loadgame(filename);
return new MessageStatus(id, true);
} catch (Exception e) {
e.printStackTrace();
return new MessageStatus(id, false, e.getMessage());
}
}
}
Methods:
MethodJavadoc
execute
getID
jfreerails.network.specifics.LogOnRequest
Javadoc:
/** * A client sends an instance of this class to the server when it wishes to log * on. * * @author Luke * */
Source code:
/**
* A client sends an instance of this class to the server when it wishes to log
* on.
*
* @author Luke
*
*/
public class LogOnRequest implements FreerailsSerializable {
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof LogOnRequest))
return false;
final LogOnRequest logOnRequest = (LogOnRequest) o;
if (password != null ? !password.equals(logOnRequest.password)
: logOnRequest.password != null)
return false;
if (username != null ? !username.equals(logOnRequest.username)
: logOnRequest.username != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = (username != null ? username.hashCode() : 0);
result = 29 * result + (password != null ? password.hashCode() : 0);
return result;
}
private static final long serialVersionUID = 3257854263924240949L;
private final String username;
private final String password;
public LogOnRequest(String username, String password) {
this.username = username;
this.password = password;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
}
Methods:
MethodJavadoc
getPassword
getUsername/** Returns the username associated with this log-on request. @return the username */
jfreerails.network.specifics.LogOnResponse
Javadoc:
/** * Stores the result of a request to log onto the server. * * @author Luke * */
Source code:
/**
* Stores the result of a request to log onto the server.
*
* @author Luke
*
*/
public class LogOnResponse implements FreerailsSerializable {
private static final long serialVersionUID = 3690479099844311344L;
private final boolean successful;
private final int playerNumber;
private final String message;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof LogOnResponse))
return false;
final LogOnResponse logOnResponse = (LogOnResponse) o;
if (playerNumber != logOnResponse.playerNumber)
return false;
if (successful != logOnResponse.successful)
return false;
if (message != null ? !message.equals(logOnResponse.message)
: logOnResponse.message != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = (successful ? 1 : 0);
result = 29 * result + playerNumber;
result = 29 * result + (message != null ? message.hashCode() : 0);
return result;
}
private LogOnResponse(boolean success, int i, String s) {
this.successful = success;
this.playerNumber = i;
this.message = s;
}
public static LogOnResponse accepted(int playerNumber) {
return new LogOnResponse(true, playerNumber, null);
}
public static LogOnResponse rejected(String reason) {
return new LogOnResponse(false, -1, reason);
}
public int getPlayerID() {
return playerNumber;
}
public String getMessage() {
return message;
}
public boolean isSuccessful() {
return successful;
}
}
Methods:
MethodJavadoc
accepted
getMessage
getPlayerID
isSuccessful
rejected
jfreerails.network.specifics.MoveChainFork
Javadoc:
/** * * A central point at which a client may register to receive moves which have * been committed. * * @author Luke * @author rob */
Source code:
/**
*
* A central point at which a client may register to receive moves which have
* been committed.
*
* @author Luke
* @author rob
*/
final public class MoveChainFork implements MoveReceiver {
private final ArrayList<MoveReceiver> moveReceivers = new ArrayList<MoveReceiver>();
private final ArrayList<MoveReceiver> splitMoveReceivers = new ArrayList<MoveReceiver>();
private final ArrayList<WorldListListener> listListeners = new ArrayList<WorldListListener>();
private final ArrayList<WorldMapListener> mapListeners = new ArrayList<WorldMapListener>();
private long lastTickTime = System.currentTimeMillis();
public long getLastTickTime() {
return lastTickTime;
}
public MoveChainFork() {
// do nothing
}
public void addMapListener(WorldMapListener l) {
mapListeners.add(l);
}
public void removeMapListener(WorldMapListener l) {
mapListeners.remove(l);
}
public void removeCompleteMoveReceiver(MoveReceiver moveReceiver) {
if (null == moveReceiver) {
throw new NullPointerException();
}
moveReceivers.remove(moveReceiver);
}
public void addCompleteMoveReceiver(MoveReceiver moveReceiver) {
if (null == moveReceiver) {
throw new NullPointerException();
}
moveReceivers.add(moveReceiver);
}
public void addSplitMoveReceiver(MoveReceiver moveReceiver) {
if (null == moveReceiver) {
throw new NullPointerException();
}
splitMoveReceivers.add(moveReceiver);
}
public void addListListener(WorldListListener listener) {
if (null == listener) {
throw new NullPointerException();
}
listListeners.add(listener);
}
public void processMove(Move move) {
for (int i = 0; i < moveReceivers.size(); i++) {
MoveReceiver m = moveReceivers.get(i);
m.processMove(move);
}
splitMove(move);
}
private void splitMove(Move move) {
if (move instanceof UndoMove) {
UndoMove undoneMove = (UndoMove) move;
move = undoneMove.getUndoneMove();
}
if (move instanceof CompositeMove) {
ImList<Move> moves = ((CompositeMove) move).getMoves();
for (int i = 0; i < moves.size(); i++) {
splitMove(moves.get(i));
}
} else {
for (int i = 0; i < splitMoveReceivers.size(); i++) {
MoveReceiver m = splitMoveReceivers.get(i);
m.processMove(move);
}
if (move instanceof AddItemToListMove) {
AddItemToListMove mm = (AddItemToListMove) move;
sendItemAdded(mm.getKey(), mm.getIndex(), mm.getPrincipal());
} else if (move instanceof ChangeItemInListMove) {
ChangeItemInListMove mm = (ChangeItemInListMove) move;
sendListUpdated(mm.getKey(), mm.getIndex(), mm.getPrincipal());
} else if (move instanceof RemoveItemFromListMove) {
RemoveItemFromListMove mm = (RemoveItemFromListMove) move;
sendItemRemoved(mm.getKey(), mm.getIndex(), mm.getPrincipal());
} else if (move instanceof MapUpdateMove) {
Rectangle r = ((MapUpdateMove) move).getUpdatedTiles();
sendMapUpdated(r);
} else if (move instanceof TimeTickMove) {
long currentTime = System.currentTimeMillis();
lastTickTime = currentTime;
}
}
}
private void sendMapUpdated(Rectangle r) {
for (int i = 0; i < mapListeners.size(); i++) {
WorldMapListener l = mapListeners.get(i);
l.tilesChanged(r);
}
}
private void sendItemAdded(KEY key, int index, FreerailsPrincipal p) {
for (int i = 0; i < listListeners.size(); i++) {
WorldListListener l = listListeners.get(i);
l.itemAdded(key, index, p);
}
}
private void sendItemRemoved(KEY key, int index, FreerailsPrincipal p) {
for (int i = 0; i < listListeners.size(); i++) {
WorldListListener l = listListeners.get(i);
l.itemRemoved(key, index, p);
}
}
private void sendListUpdated(KEY key, int index, FreerailsPrincipal p) {
for (int i = 0; i < listListeners.size(); i++) {
WorldListListener l = listListeners.get(i);
l.listUpdated(key, index, p);
}
}
}
Methods:
MethodJavadoc
addCompleteMoveReceiver
addListListener
addMapListener
addSplitMoveReceiver
getLastTickTime
processMove
removeCompleteMoveReceiver
removeMapListener
sendItemAdded
sendItemRemoved
sendListUpdated
sendMapUpdated
splitMove
jfreerails.network.specifics.MovePrecommitter
Javadoc:
/** * The class pre-commits moves we intend to send to the server and either fully * commits or undoes them depending on the server's response. Note, this class * does not actually send or receive moves, instead you should call * <code>toServer(.)</code> when a move has been sent to the server and * <code>fromServer(.)</code> when a Move or MoveStatus has been received from * the server. * * @author Luke * */
Source code:
/**
* The class pre-commits moves we intend to send to the server and either fully
* commits or undoes them depending on the server's response. Note, this class
* does not actually send or receive moves, instead you should call
* <code>toServer(.)</code> when a move has been sent to the server and
* <code>fromServer(.)</code> when a Move or MoveStatus has been received from
* the server.
*
* @author Luke
*
*/
public class MovePrecommitter {
private static class PreMoveAndMove implements FreerailsSerializable {
private static final long serialVersionUID = 3256443607635342897L;
final Move m;
final PreMove pm;
PreMoveAndMove(PreMove preMove, Move move) {
m = move;
pm = preMove;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof PreMoveAndMove))
return false;
final PreMoveAndMove preMoveAndMove = (PreMoveAndMove) o;
if (m != null ? !m.equals(preMoveAndMove.m)
: preMoveAndMove.m != null)
return false;
if (pm != null ? !pm.equals(preMoveAndMove.pm)
: preMoveAndMove.pm != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = (m != null ? m.hashCode() : 0);
result = 29 * result + (pm != null ? pm.hashCode() : 0);
return result;
}
}
private static final Logger logger = Logger
.getLogger(MovePrecommitter.class.getName());
/**
* Whether the first move on the uncommitted list failed to go through on
* the last try.
*/
boolean blocked = false;
/**
* List of moves and premoves that have been sent to the server and executed
* on the local world object.
*/
final LinkedList<FreerailsSerializable> precomitted = new LinkedList<FreerailsSerializable>();
/**
* List of moves and premoves that have been sent to the server but not
* executed on the local world object.
*/
final LinkedList<FreerailsSerializable> uncomitted = new LinkedList<FreerailsSerializable>();
private final World w;
MovePrecommitter(World w) {
this.w = w;
}
void fromServer(Move m) {
logger.finest("Move from server: " + m.toString());
rollBackPrecommittedMoves();
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
}
/** Indicates that the server has processed a move we sent. */
void fromServer(MoveStatus ms) {
precommitMoves();
if (precomitted.size() > 0) {
Move m = (Move) precomitted.removeFirst();
if (!ms.ok) {
logger.info("Move rejected by server: " + ms.message);
MoveStatus undoStatus = m.undoMove(w, Player.AUTHORITATIVE);
if (!undoStatus.ok) {
throw new IllegalStateException();
}
} else {
logger.finest("Move accepted by server: " + m.toString());
}
} else {
if (!ms.ok) {
logger.fine("Clear the blockage " + ms.message);
uncomitted.removeFirst();
precommitMoves();
} else {
throw new IllegalStateException();
}
}
}
Move fromServer(PreMove pm) {
Move generatedMove = pm.generateMove(w);
fromServer(generatedMove);
return generatedMove;
}
void fromServer(PreMoveStatus pms) {
rollBackPrecommittedMoves();
PreMove pm = (PreMove) uncomitted.removeFirst();
if (pms.ms.ok) {
logger.finest("PreMove accepted by server: " + pms.toString());
Move m = pm.generateMove(w);
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
if (!ms.ok) {
throw new IllegalStateException();
}
} else {
logger.info("PreMove rejected by server: " + pms.ms.message);
}
precommitMoves();
}
void precommitMoves() {
blocked = false;
while (uncomitted.size() > 0 && !blocked) {
Object first = uncomitted.getFirst();
if (first instanceof Move) {
Move m = (Move) first;
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
if (ms.ok) {
uncomitted.removeFirst();
precomitted.addLast(m);
} else {
blocked = true;
}
} else if (first instanceof PreMove) {
PreMove pm = (PreMove) first;
Move m = pm.generateMove(w);
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
if (ms.ok) {
uncomitted.removeFirst();
PreMoveAndMove pmam = new PreMoveAndMove(pm, m);
precomitted.addLast(pmam);
} else {
blocked = true;
}
}
}
}
/**
* Undoes each of the precommitted moves and puts them back on the
* uncommitted list.
*/
private void rollBackPrecommittedMoves() {
while (precomitted.size() > 0) {
Object last = precomitted.removeLast();
Move move2undo;
FreerailsSerializable obj2add2uncomitted;
if (last instanceof Move) {
move2undo = (Move) last;
obj2add2uncomitted = move2undo;
} else if (last instanceof PreMoveAndMove) {
PreMoveAndMove pmam = (PreMoveAndMove) last;
move2undo = pmam.m;
obj2add2uncomitted = pmam.pm;
} else {
throw new IllegalStateException();
}
MoveStatus ms = move2undo.undoMove(w, Player.AUTHORITATIVE);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
uncomitted.addFirst(obj2add2uncomitted);
}
}
void toServer(Move m) {
uncomitted.addLast(m);
precommitMoves();
}
Move toServer(PreMove pm) {
uncomitted.addLast(pm);
precommitMoves();
if (blocked) {
return pm.generateMove(w);
}
PreMoveAndMove pmam = (PreMoveAndMove) precomitted.getLast();
return pmam.m;
}
}
Methods:
MethodJavadoc
fromServer/** Indicates that the server has processed a move we sent. */
fromServer
fromServer
fromServer
precommitMoves
rollBackPrecommittedMoves/**
toServer
toServer
jfreerails.network.specifics.MoveReceiver
Javadoc:
/** * Accepts a Move without the caller knowing where its going. TODO replace with * MoveExecutor where the moves are expected to be executed. * * @author Luke */
Source code:
/**
* Accepts a Move without the caller knowing where its going. TODO replace with
* MoveExecutor where the moves are expected to be executed.
*
* @author Luke
*/
public interface MoveReceiver {
void processMove(Move move);
}
Methods:
MethodJavadoc
processMove
jfreerails.network.specifics.NameAndPassword
Javadoc:
/** * Used by the server to store a player's username and password. * * @author Luke * */
Source code:
/**
* Used by the server to store a player's username and password.
*
* @author Luke
*
*/
public class NameAndPassword implements Serializable {
private static final long serialVersionUID = 3258409551740155956L;
public final String password;
public final String username;
public NameAndPassword(String u, String p) {
username = u;
password = p;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof NameAndPassword))
return false;
NameAndPassword test = (NameAndPassword) obj;
return test.password.equals(password) && test.username.equals(username);
}
@Override
public int hashCode() {
int result = 17;
result = result * 37 + password.hashCode();
result = result * 37 + username.hashCode();
return result;
}
@Override
public String toString() {
return username;
}
}
No methods in this class.
jfreerails.network.specifics.NewGameMessage2Server
Javadoc:
/** * Request to start a game on a new map. * * @author Luke * */
Source code:
/**
* Request to start a game on a new map.
*
* @author Luke
*
*/
public class NewGameMessage2Server implements Message2Server {
private static final long serialVersionUID = 3256723961743422513L;
private final int id;
private final String mapName;
public NewGameMessage2Server(int id, String s) {
this.id = id;
this.mapName = s;
}
public int getID() {
return id;
}
public MessageStatus execute(ServerControlInterface server) {
try {
server.newGame(mapName);
return new MessageStatus(id, true);
} catch (Exception e) {
return new MessageStatus(id, false, e.getMessage());
}
}
/**
* TODO This would be better implemented in a config file, or better still
* dynamically determined by scanning the directory.
*/
public static String[] getMapNames() {
return new String[] { "South America", "Small South America" };
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof NewGameMessage2Server))
return false;
final NewGameMessage2Server newGameMessage2Server = (NewGameMessage2Server) o;
if (id != newGameMessage2Server.id)
return false;
if (!mapName.equals(newGameMessage2Server.mapName))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + mapName.hashCode();
return result;
}
}
Methods:
MethodJavadoc
execute
getID
getMapNames/**
jfreerails.network.specifics.RefreshListOfGamesMessage2Server
Javadoc:
/** Tells the server to check the filesystem for changes to the available new maps and saved games. * @author Luke * */
Source code:
/** Tells the server to check the filesystem for changes to the available new maps and saved games.
* @author Luke
* */
public class RefreshListOfGamesMessage2Server implements Message2Server {
private static final long serialVersionUID = -8745171955732354168L;
private final int id;
public MessageStatus execute(ServerControlInterface server) {
server.refreshSavedGames();
return new MessageStatus(id, true);
}
public int getID() {
return id;
}
public RefreshListOfGamesMessage2Server(final int id) {
super();
this.id = id;
}
@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final RefreshListOfGamesMessage2Server other = (RefreshListOfGamesMessage2Server) obj;
if (id != other.id)
return false;
return true;
}
}
Methods:
MethodJavadoc
execute
getID
jfreerails.network.specifics.SaveGameMessage2Server
Javadoc:
/** * A request to save the game. * * @author Luke * */
Source code:
/**
* A request to save the game.
*
* @author Luke
*
*/
public class SaveGameMessage2Server implements Message2Server {
private static final long serialVersionUID = 3257281452725777209L;
private final int id;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof SaveGameMessage2Server))
return false;
final SaveGameMessage2Server saveGameMessage2Server = (SaveGameMessage2Server) o;
if (id != saveGameMessage2Server.id)
return false;
if (!filename.equals(saveGameMessage2Server.filename))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + filename.hashCode();
return result;
}
private final String filename;
public SaveGameMessage2Server(int id, String s) {
this.id = id;
this.filename = s;
}
public int getID() {
return id;
}
public MessageStatus execute(ServerControlInterface server) {
try {
server.savegame(filename);
return new MessageStatus(id, true);
} catch (Exception e) {
return new MessageStatus(id, false, e.getMessage());
}
}
}
Methods:
MethodJavadoc
execute
getID
jfreerails.network.specifics.SavedGamesManager
Javadoc:
/** * Defines methods that let the server load and save game states, and get blank * maps for new games. * * @author Luke * */
Source code:
/**
* Defines methods that let the server load and save game states, and get blank
* maps for new games.
*
* @author Luke
*
*/
public interface SavedGamesManager {
String[] getSaveGameNames();
String[] getNewMapNames();
void saveGame(Serializable w, String s) throws IOException;
Serializable loadGame(String name) throws IOException;
Serializable newMap(String name) throws IOException;
}
Methods:
MethodJavadoc
getNewMapNames
getSaveGameNames
loadGame
newMap
saveGame
jfreerails.network.specifics.SavedGamesManager4UnitTests
Javadoc:
/** * Stores saved games in memory rather than on disk. * * @author Luke * */
Source code:
/**
* Stores saved games in memory rather than on disk.
*
* @author Luke
*
*/
public class SavedGamesManager4UnitTests implements SavedGamesManager {
private String[] mapsAvailable = { "map1", "map2" };
private final HashMap<String, Serializable> savedGames = new HashMap<String, Serializable>();
public String[] getSaveGameNames() {
Object[] keys = savedGames.keySet().toArray();
String[] names = new String[keys.length];
for (int i = 0; i < names.length; i++) {
names[i] = (String) keys[i];
}
return names;
}
public String[] getNewMapNames() {
return mapsAvailable.clone();
}
public void saveGame(Serializable w, String name) throws IOException {
// Make a copy so that the saved version's state cannot be changed.
Serializable copy = Utils.cloneBySerialisation(w);
this.savedGames.put(name, copy);
}
public Serializable loadGame(String name) throws IOException {
Serializable o = savedGames.get(name);
return Utils.cloneBySerialisation(o);
}
public Serializable newMap(String name) throws IOException {
return new WorldImpl(10, 10);
}
}
Methods:
MethodJavadoc
getNewMapNames
getSaveGameNames
loadGame
newMap
saveGame
jfreerails.network.specifics.ServerCommandReceiver
Javadoc:
/** * Defines a method that accepts a command to be sent to the server. * * @author Luke * */
Source code:
/**
* Defines a method that accepts a command to be sent to the server.
*
* @author Luke
*
*/
public interface ServerCommandReceiver {
void sendCommand(Message2Server c);
}
Methods:
MethodJavadoc
sendCommand
jfreerails.network.specifics.ServerGameModel
Javadoc:
/** * Defines methods on a GameModel that let the server load and initiate, and * save it. * * @author Luke * */
Source code:
/**
* Defines methods on a GameModel that let the server load and initiate, and
* save it.
*
* @author Luke
*
*/
public interface ServerGameModel extends GameModel, Serializable {
void setWorld(World w, String[] passwords);
World getWorld();
String[] getPasswords();
void init(MoveReceiver moveExecutor);
void write(ObjectOutputStream objectOut) throws IOException;
}
Methods:
MethodJavadoc
getPasswords
getWorld
init
setWorld
write
jfreerails.network.specifics.SetPropertyMessage2Client
Javadoc:
/** * A Message2Client that lets the server set a property (for example, the list * of saved games available) on a client. * * @author Luke * */
Source code:
/**
* A Message2Client that lets the server set a property (for example, the list
* of saved games available) on a client.
*
* @author Luke
*
*/
public class SetPropertyMessage2Client implements Message2Client {
private static final long serialVersionUID = 3544392521746034740L;
private final int id;
private final ClientProperty key;
private final FreerailsSerializable value;
public SetPropertyMessage2Client(int id, ClientProperty key,
FreerailsSerializable value) {
if (null == key || null == value)
throw new NullPointerException();
this.id = id;
this.key = key;
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof SetPropertyMessage2Client))
return false;
final SetPropertyMessage2Client setPropertyMessage2Client = (SetPropertyMessage2Client) o;
if (id != setPropertyMessage2Client.id)
return false;
if (!key.equals(setPropertyMessage2Client.key))
return false;
if (!value.equals(setPropertyMessage2Client.value))
return false;
return true;
}
public MessageStatus execute(ClientControlInterface client) {
client.setProperty(key, value);
return new MessageStatus(id, true);
}
public int getID() {
return id;
}
@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + key.hashCode();
result = 29 * result + value.hashCode();
return result;
}
}
Methods:
MethodJavadoc
execute
getID
jfreerails.network.specifics.SetWorldMessage2Client
Javadoc:
/** * Sent from the server to the client when (i) a new game is started, (ii) a * game is loaded, or (iii) the client connects to a game in progress. * * @author Luke * */
Source code:
/**
* Sent from the server to the client when (i) a new game is started, (ii) a
* game is loaded, or (iii) the client connects to a game in progress.
*
* @author Luke
*
*/
@Immutable
public class SetWorldMessage2Client implements Message2Client {
private static final long serialVersionUID = 3257570619972269362L;
private final int id;
private final World world;
/**
* Note, makes a defensive copy of the world object passed to it.
*/
public SetWorldMessage2Client(int id, World world) {
this.id = id;
this.world = world.defensiveCopy();
}
public MessageStatus execute(ClientControlInterface client) {
client.setGameModel(world.defensiveCopy());
return new MessageStatus(id, true);
}
public int getID() {
return id;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof SetWorldMessage2Client))
return false;
final SetWorldMessage2Client setWorldMessage2Client = (SetWorldMessage2Client) o;
if (id != setWorldMessage2Client.id)
return false;
if (!world.equals(setWorldMessage2Client.world))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + world.hashCode();
return result;
}
}
Methods:
MethodJavadoc
execute
getID
jfreerails.network.specifics.SimpleServerGameModel
Javadoc:
/** * A ServerGameModel that has a world object but no automation. * * @author Luke * */
Source code:
/**
* A ServerGameModel that has a world object but no automation.
*
* @author Luke
*
*/
public class SimpleServerGameModel implements ServerGameModel {
private static final long serialVersionUID = 3546074757457131826L;
private World w;
private String[] passwords;
public void setWorld(World w, String[] passwords) {
this.w = w;
this.passwords = passwords.clone();
}
public World getWorld() {
return w;
}
public void init(MoveReceiver moveExecuter) {
}
public void write(ObjectOutputStream objectOut) throws IOException {
}
public void update() {
}
public void listUpdated(KEY key, int index, FreerailsPrincipal principal) {
}
public void itemAdded(KEY key, int index, FreerailsPrincipal principal) {
}
public void itemRemoved(KEY key, int index, FreerailsPrincipal principal) {
}
public String[] getPasswords() {
return passwords.clone();
}
}
Methods:
MethodJavadoc
getPasswords
getWorld
init
itemAdded
itemRemoved
listUpdated/**
setWorld
update
write
jfreerails.network.specifics.UntriedMoveReceiver
Javadoc:
/** * Lets the caller test moves. * * @author rob * */
Source code:
/**
* Lets the caller test moves.
*
* @author rob
*
*/
public interface UntriedMoveReceiver extends MoveReceiver {
MoveStatus tryDoMove(Move move);
void processPreMove(PreMove pm);
}
Methods:
MethodJavadoc
processPreMove
tryDoMove
jfreerails.server.CalcSupplyAtStations
Javadoc:
/** * This class loops through all of the known stations and recalculates the * cargoes that they supply, demand, and convert. * * @author Scott Bennett Created: 19th May 2003 */
Source code:
/**
* This class loops through all of the known stations and recalculates the
* cargoes that they supply, demand, and convert.
*
* @author Scott Bennett Created: 19th May 2003
*/
public class CalcSupplyAtStations {
private final World w;
private final MoveReceiver moveReceiver;
/**
*
* Constructor, currently called from GUIComponentFactory.
*
* @param world
* The World object that contains all about the game world
*
*/
public CalcSupplyAtStations(World world, MoveReceiver mr) {
this.w = world;
this.moveReceiver = mr;
}
/**
*
* Loop through each known station, call calculations method.
*
*/
public void doProcessing() {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
NonNullElements iterator = new NonNullElements(KEY.STATIONS, w,
principal);
while (iterator.next()) {
StationModel stationBefore = (StationModel) iterator
.getElement();
CalcCargoSupplyRateAtStation supplyRate;
supplyRate = new CalcCargoSupplyRateAtStation(w,
stationBefore.x, stationBefore.y);
StationModel stationAfter = supplyRate
.calculations(stationBefore);
if (!stationAfter.equals(stationBefore)) {
Move move = new ChangeStationMove(iterator.getIndex(),
stationBefore, stationAfter, principal);
this.moveReceiver.processMove(move);
}
}
}
}
}
Methods:
MethodJavadoc
doProcessing/**
jfreerails.server.CargoAtStationsGenerator
Javadoc:
/** * This class loops over the list of stations and adds cargo depending on what * the surrounding tiles supply. * * @author Luke * */
Source code:
/**
* This class loops over the list of stations and adds cargo depending on what
* the surrounding tiles supply.
*
* @author Luke
*
*/
public class CargoAtStationsGenerator implements FreerailsServerSerializable {
private static final long serialVersionUID = 3834596504072959796L;
public CargoAtStationsGenerator() {
}
/** Call this method once a month. */
public void update(World w, MoveReceiver moveReceiver) {
for (int k = 0; k < w.getNumberOfPlayers(); k++) {
FreerailsPrincipal principal = w.getPlayer(k).getPrincipal();
NonNullElements nonNullStations = new NonNullElements(KEY.STATIONS,
w, principal);
while (nonNullStations.next()) {
StationModel station = (StationModel) nonNullStations
.getElement();
SupplyAtStation supply = station.getSupply();
ImmutableCargoBundle cargoBundle = (ImmutableCargoBundle) w
.get(principal, KEY.CARGO_BUNDLES,
station.getCargoBundleID());
MutableCargoBundle before = new MutableCargoBundle(cargoBundle);
MutableCargoBundle after = new MutableCargoBundle(cargoBundle);
int stationNumber = nonNullStations.getIndex();
/*
* Get the iterator from a copy to avoid a
* ConcurrentModificationException if the amount gets set to
* zero and the CargoBatch removed from the cargo bundle. LL
*/
Iterator<CargoBatch> it = after.toImmutableCargoBundle()
.cargoBatchIterator();
while (it.hasNext()) {
CargoBatch cb = it.next();
int amount = after.getAmount(cb);
if (amount > 0) {
// (23/24)^12 = 0.60
after.setAmount(cb, amount * 23 / 24);
}
}
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
int amountSupplied = supply.getSupply(i);
if (amountSupplied > 0) {
CargoBatch cb = new CargoBatch(i, station.x, station.y,
0, stationNumber);
int amountAlready = after.getAmount(cb);
// Obtain the month
GameTime time = w.currentTime();
GameCalendar calendar = (GameCalendar) w
.get(ITEM.CALENDAR);
int month = calendar.getMonth(time.getTicks());
int amountAfter = calculateAmountToAdd(amountSupplied,
month)
+ amountAlready;
after.setAmount(cb, amountAfter);
}
}
Move m = new ChangeCargoBundleMove(before
.toImmutableCargoBundle(), after
.toImmutableCargoBundle(), station.getCargoBundleID(),
principal);
moveReceiver.processMove(m);
}
}
}
int calculateAmountToAdd(int amountSuppliedPerYear, int month) {
// Note, jan is month 0.
int totalAtMonthEnd = amountSuppliedPerYear * (month + 1) / 12;
int totalAtMonthStart = amountSuppliedPerYear * (month) / 12;
int amount = totalAtMonthEnd - totalAtMonthStart;
return amount;
}
}
Methods:
MethodJavadoc
calculateAmountToAdd
update/** Call this method once a month. */
jfreerails.server.CityEconomicModel
Javadoc:
/** * This class is lets the server analyse and alter cities. * * @author Luke * */
Source code:
/**
* This class is lets the server analyse and alter cities.
*
* @author Luke
*
*/
class CityEconomicModel {
/** Stores a tile type and its location. */
private class Tile {
final Point p;
final TerrainType type;
public Tile(final Point p, final TerrainType type) {
this.p = p;
this.type = type;
}
}
final ArrayList<Tile> urbanTiles = new ArrayList<Tile>();
final ArrayList<Tile> industryTiles = new ArrayList<Tile>();
final ArrayList<TerrainType> industriesNotAtCity = new ArrayList<TerrainType>();
final ArrayList<Tile> resourceTiles = new ArrayList<Tile>();
final ArrayList<Point> clearTiles = new ArrayList<Point>();
/** The number of stations within this city's bounds. */
int stations = 0;
void addTile(TerrainType type) {
Random rand = new Random();
// Pick a spot at random at which to place the tile.
if (clearTiles.size() > 0) {
int tilePos = rand.nextInt(clearTiles.size());
Point p = clearTiles.remove(tilePos);
if (type.getCategory().equals(TerrainType.Category.Urban)) {
urbanTiles.add(new Tile(p, type));
} else if (type.getCategory().equals(TerrainType.Category.Industry)) {
industryTiles.add(new Tile(p, type));
industriesNotAtCity.remove(type);
} else if (type.getCategory().equals(TerrainType.Category.Country)) {
throw new IllegalArgumentException(
"call remove(.) to replace a city tile with a country tile!");
} else if (type.getCategory().equals(TerrainType.Category.Resource)) {
resourceTiles.add(new Tile(p, type));
}
}
}
void loadFromMap(ReadOnlyWorld w, int cityID) {
/* Reset lists of tiles. */
urbanTiles.clear();
industryTiles.clear();
clearTiles.clear();
resourceTiles.clear();
/* Set up the list of industries not at the city. */
industriesNotAtCity.clear();
for (int i = 0; i < w.size(SKEY.TERRAIN_TYPES); i++) {
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
if (type.getCategory().equals(TerrainType.Category.Industry)) {
industriesNotAtCity.add(type);
}
}
stations = 0;
/* Identify city's bounds. */
Rectangle mapRect = new Rectangle(0, 0, w.getMapWidth(), w
.getMapHeight());
CityModel city = (CityModel) w.get(SKEY.CITIES, cityID);
Rectangle cityArea = new Rectangle(city.getCityX() - 3,
city.getCityY() - 3, 7, 7);
cityArea = cityArea.intersection(mapRect);
/* Count tile types. */
for (int x = cityArea.x; x < cityArea.x + cityArea.width; x++) {
for (int y = cityArea.y; y < cityArea.y + cityArea.height; y++) {
FreerailsTile tile = (FreerailsTile) w.getTile(x, y);
/* Count the number of stations at the city. */
if (tile.getTrackPiece().getTrackRule().isStation()) {
stations++;
}
int terrainTypeNumber = tile.getTerrainTypeID();
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES,
terrainTypeNumber);
if (type.getCategory().equals(TerrainType.Category.Urban)) {
urbanTiles.add(new Tile(new Point(x, y), type));
} else if (type.getCategory().equals(
TerrainType.Category.Industry)) {
industryTiles.add(new Tile(new Point(x, y), type));
industriesNotAtCity.remove(type);
} else if (type.getCategory().equals(
TerrainType.Category.Country)) {
clearTiles.add(new Point(x, y));
} else if (type.getCategory().equals(
TerrainType.Category.Resource)) {
resourceTiles.add(new Tile(new Point(x, y), type));
}
}
}
}
int size() {
return this.urbanTiles.size() + this.industryTiles.size()
+ this.resourceTiles.size();
}
void write2map(World w) {
for (int i = 0; i < urbanTiles.size(); i++) {
writeTile(w, urbanTiles.get(i));
}
for (int i = 0; i < industryTiles.size(); i++) {
writeTile(w, industryTiles.get(i));
}
for (int i = 0; i < resourceTiles.size(); i++) {
writeTile(w, resourceTiles.get(i));
}
}
private void writeTile(World w, Tile tile) {
int type = 0;
while (!w.get(SKEY.TERRAIN_TYPES, type).equals(tile.type)) {
type++;
}
int x = tile.p.x;
int y = tile.p.y;
FreerailsTile fTile = (FreerailsTile) w.getTile(x, y);
fTile = FreerailsTile.getInstance(type, fTile.getTrackPiece());
w.setTile(x, y, fTile);
}
}
Methods:
MethodJavadoc
addTile
loadFromMap
size
write2map
writeTile
jfreerails.server.CitySAXParser
Javadoc:
/** * * Class to parse an xml file that contains city names and co-ords. Upon reading * in the data, its stored in KEY.CITIES. * * @author Scott Bennett Date: 31st March 2003 */
Source code:
/**
*
* Class to parse an xml file that contains city names and co-ords. Upon reading
* in the data, its stored in KEY.CITIES.
*
* @author Scott Bennett Date: 31st March 2003
*/
public class CitySAXParser extends DefaultHandler {
private final Vector<CityModel> cities;
private final World world;
public CitySAXParser(World w) throws SAXException {
world = w;
cities = new Vector<CityModel>();
}
@Override
public void endDocument() throws SAXException {
for (int i = 0; i < cities.size(); i++) {
CityModel tempCity = cities.elementAt(i);
world.add(SKEY.CITIES, new CityModel(tempCity.getCityName(),
tempCity.getCityX(), tempCity.getCityY()));
}
}
@Override
public void startElement(String namespaceURI, String sName, String qName,
Attributes attrs) throws SAXException {
String cityName = null;
int x = 0;
int y = 0;
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String aName = attrs.getLocalName(i); // Attr name
if (aName.equals("")) {
aName = attrs.getQName(i);
}
// put values in CityModel obj
if (aName.equals("name")) {
cityName = attrs.getValue(i);
}
if (aName.equals("x")) {
x = Integer.parseInt(attrs.getValue(i));
}
if (aName.equals("y")) {
y = Integer.parseInt(attrs.getValue(i));
CityModel city = new CityModel(cityName, x, y);
cities.addElement(city);
}
}
// end for loop
}
// end if
}
// end startElement method
}
Methods:
MethodJavadoc
endDocument
startElement
jfreerails.server.CityTilePositioner
Javadoc:
/** * This class initialises cities and controls their growth. It makes changes to * directly to the world object, so if the game has already started, use * WorldDifferences and MapDiffMove to pass changes to the clients. * * @author Luke * */
Source code:
/**
* This class initialises cities and controls their growth. It makes changes to
* directly to the world object, so if the game has already started, use
* WorldDifferences and MapDiffMove to pass changes to the clients.
*
* @author Luke
*
*/
public class CityTilePositioner {
Random random = new Random();
ArrayList<TerrainType> urbanTerrainTypes = new ArrayList<TerrainType>();
ArrayList<TerrainType> industryTerrainTypes = new ArrayList<TerrainType>();
ArrayList<TerrainType> resourceTerrainTypes = new ArrayList<TerrainType>();
World w;
public CityTilePositioner(World w) {
this.w = w;
// get the different types of Urban/Industry/Resource terrain
for (int i = 0; i < w.size(SKEY.TERRAIN_TYPES); i++) {
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
switch (type.getCategory().ordinal()) {
case 0:
urbanTerrainTypes.add(type);
break;
case 6:
industryTerrainTypes.add(type);
break;
case 7:
resourceTerrainTypes.add(type);
break;
}
}
}
void initCities() {
final int numCities = w.size(SKEY.CITIES);
CityEconomicModel[] cities = new CityEconomicModel[numCities];
for (int cityId = 0; cityId < numCities; cityId++) {
CityEconomicModel city = new CityEconomicModel();
city.loadFromMap(w, cityId);
final int urbanTiles = 2 + random.nextInt(3);
for (int i = 0; i < urbanTiles; i++) {
addUrbanTile(city);
}
final int industryTiles = random.nextInt(3);
for (int i = 0; i < industryTiles; i++) {
addIndustryTile(city);
}
final int resourceTiles = random.nextInt(3);
for (int i = 0; i < resourceTiles; i++) {
addResourceTile(city);
}
city.write2map(w);
cities[cityId] = city;
}
}
private void addResourceTile(CityEconomicModel city) {
int tileTypeNo = random.nextInt(resourceTerrainTypes.size());
TerrainType type = resourceTerrainTypes.get(tileTypeNo);
city.addTile(type);
}
private void addIndustryTile(CityEconomicModel city) {
int size = city.industriesNotAtCity.size();
if (size > 0) {
int tileTypeNo = random.nextInt(size);
TerrainType type = city.industriesNotAtCity.get(tileTypeNo);
city.addTile(type);
}
}
private void addUrbanTile(CityEconomicModel city) {
int tileTypeNo = random.nextInt(urbanTerrainTypes.size());
TerrainType type = urbanTerrainTypes.get(tileTypeNo);
city.addTile(type);
}
void growCities() {
final int numCities = w.size(SKEY.CITIES);
/*
* At some stage this will be refined to take into account how much
* cargo has been picked up and delivered and what city tiles are
* already present.
*/
for (int cityId = 0; cityId < numCities; cityId++) {
CityEconomicModel city = new CityEconomicModel();
city.loadFromMap(w, cityId);
// Only increase cities with stations and less than 16 tiles
if (city.size() < 16 && city.stations > 0) {
switch (random.nextInt(10)) {
case 0:
case 1:
addResourceTile(city); // 20% chance
break;
case 2:
case 3:
case 4:
case 5:
addUrbanTile(city); // 40% chance
break;
case 6:
addIndustryTile(city); // 10% chance
break;
default:
// do nothing, 30% chance
break;
}
city.write2map(w);
}
}
}
}
Methods:
MethodJavadoc
addIndustryTile
addResourceTile
addUrbanTile
growCities
initCities
jfreerails.server.InputCityNames
Javadoc:
/** * Class that calls the object to input the City names and co-ords from an xml * file. * * @author Scott Bennett Date: 31st March 2003 */
Source code:
/**
* Class that calls the object to input the City names and co-ords from an xml
* file.
*
* @author Scott Bennett Date: 31st March 2003
*/
public class InputCityNames {
public static void readCityNames(World w, URL filename) throws SAXException {
InputSource is = new InputSource(filename.toString());
DefaultHandler handler = new CitySAXParser(w);
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(is, handler);
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
}
}
}
Methods:
MethodJavadoc
readCityNames
jfreerails.server.InterestChargeMoveGenerator
Javadoc:
/** * This class iterates over the entries in the BankAccount and counts the number * of outstanding bonds, then calculates the interest due. * * @author Luke Lindsay * */
Source code:
/**
* This class iterates over the entries in the BankAccount and counts the number
* of outstanding bonds, then calculates the interest due.
*
* @author Luke Lindsay
*
*/
public class InterestChargeMoveGenerator {
private final MoveReceiver moveReceiver;
public InterestChargeMoveGenerator(MoveReceiver mr) {
this.moveReceiver = mr;
}
private static AddTransactionMove generateMove(World w,
FreerailsPrincipal principal) {
long interestDue = 0;
for (int i = 0; i < w.getNumberOfTransactions(principal); i++) {
Transaction t = w.getTransaction(principal, i);
if (t instanceof BondTransaction) {
BondTransaction bt = (BondTransaction) t;
int interestRate = bt.getType();
long bondAmount = BondTransaction.BOND_VALUE_ISSUE.getAmount();
interestDue += (interestRate * bondAmount / 100)
* bt.getQuantity();
}
}
Transaction t = new Bill(new Money(interestDue),
Transaction.Category.INTEREST_CHARGE);
return new AddTransactionMove(principal, t);
}
public void update(World w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
Move m = generateMove(w, principal);
moveReceiver.processMove(m);
}
}
}
Methods:
MethodJavadoc
generateMove
update
jfreerails.server.MapCustomizer
Javadoc:
/** * Provides methods to customize a map by adding track, stations and trains. * Intended for use in unit tests. * * @author Luke */
Source code:
/**
* Provides methods to customize a map by adding track, stations and trains.
* Intended for use in unit tests.
*
* @author Luke
*/
public class MapCustomizer {
public final World w;
private final TrackMoveProducer producer;
private final TrackPathFinder pathFinder;
private final StationBuilder stationBuilder;
private final BuildTrackStrategy bts;
public MapCustomizer() {
this(MapFixtureFactory2.getCopy());
}
public MapCustomizer(World w) {
this.w = w;
MoveExecutor me = new SimpleMoveExecutor(w, 0);
ModelRoot mr = new ModelRootImpl();
producer = new TrackMoveProducer(me, w, mr);
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
pathFinder = new TrackPathFinder(w, principal);
stationBuilder = new StationBuilder(me);
int terminalTypeID = stationBuilder.getTrackTypeID("terminal");
stationBuilder.setStationType(terminalTypeID);
bts = BuildTrackStrategy.getDefault(w);
}
public MapCustomizer buildTrack(ImPoint a, ImPoint b) throws PathNotFoundException {
pathFinder.setupSearch(a, b, bts);
pathFinder.search(-1);
List<ImPoint> pathAsPoints = pathFinder.pathAsPoints();
ImPoint from = a;
for (int i = 0; i < pathAsPoints.size(); i++) {
ImPoint to = pathAsPoints.get(i);
Step vector = Step.getInstance(to.x - from.x, to.y
- from.y);
FreerailsTile tile = (FreerailsTile) w.getTile(
from.x, from.y);
if (!tile.getTrackPiece().getTrackConfiguration().contains(vector)) {
producer.buildTrack(from, vector);
}
from = to;
}
return this;
}
public MapCustomizer buildStation(ImPoint a) {
MoveStatus ms = stationBuilder.buildStation(a);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
return this;
}
public MapCustomizer buildTrain(ImPoint a, int... stops) {
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
MutableSchedule s = new MutableSchedule();
for (int stop : stops) {
s.addOrder(new TrainOrdersModel(stop, null, false, true));
}
ImmutableSchedule defaultSchedule = s.toImmutableSchedule();
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(),
a, principal, defaultSchedule);
Move m = preMove.generateMove(w);
MoveStatus status = m.doMove(w, Player.AUTHORITATIVE);
if (!status.ok) {
throw new IllegalStateException(status.message);
}
return this;
}
/**
* Returns -1 if no station here or the id of the station if one is
* present.
*/
public int getStationId(ImPoint location) {
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
FreerailsTile tile = (FreerailsTile) w.getTile(location.x, location.y);
TrackRule trackRule = tile.getTrackPiece().getTrackRule();
if (trackRule.isStation()
&& tile.getTrackPiece().getOwnerID() == w.getID(principal)) {
for (int i = 0; i < w.size(principal, KEY.STATIONS); i++) {
StationModel station = (StationModel) w.get(principal,
KEY.STATIONS, i);
if (null != station && station.getLocation().equals(location)) {
return i;
}
}
throw new IllegalStateException();
} else {
return -1;
}
}
}
Methods:
MethodJavadoc
buildStation
buildTrack
buildTrain
getStationId/**
jfreerails.server.MapFactory
Javadoc:
/** * This class has a static method that converts an image file into a map. * * @author Luke * @author Scott Bennett (Updated 23rd Jan 2004) * * Implemented Terrain Randomisation to randomly position the terrain types for * each tile on the map. */
Source code:
/**
* This class has a static method that converts an image file into a map.
*
* @author Luke
* @author Scott Bennett (Updated 23rd Jan 2004)
*
* Implemented Terrain Randomisation to randomly position the terrain types for
* each tile on the map.
*/
public class MapFactory {
/*
* create a vector to keep track of what terrain types to 'clump'
*/
private static final Vector<Integer> countryTypes = new Vector<Integer>();
private static final Vector<Integer> non_countryTypes = new Vector<Integer>();
private static WorldImpl world;
public static void setupMap(URL map_url, WorldImpl w,
FreerailsProgressMonitor pm) {
// Setup progress monitor..
pm.setValue(0);
world = w;
Image mapImage = (new ImageIcon(map_url)).getImage();
Rectangle mapRect = new java.awt.Rectangle(0, 0, mapImage
.getWidth(null), mapImage.getHeight(null));
BufferedImage mapBufferedImage = new BufferedImage(mapRect.width,
mapRect.height, BufferedImage.TYPE_INT_ARGB);
Graphics g = mapBufferedImage.getGraphics();
g.drawImage(mapImage, 0, 0, null);
w.setupMap(mapRect.width, mapRect.height);
pm.nextStep(mapRect.width);
HashMap<Integer, Integer> rgb2TerrainType = new HashMap<Integer, Integer>();
for (int i = 0; i < w.size(SKEY.TERRAIN_TYPES); i++) {
TerrainType tilemodel = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
rgb2TerrainType.put(tilemodel.getRGB(), i);
}
TerrainType terrainTypeTile;
for (int c = 0; c < w.size(SKEY.TERRAIN_TYPES); c++) {
terrainTypeTile = (TerrainType) w.get(SKEY.TERRAIN_TYPES, c);
if (terrainTypeTile.getCategory().equals(
TerrainType.Category.Country)) {
if ((!terrainTypeTile.getTerrainTypeName().equals("Clear"))) {
countryTypes.add(new Integer(c));
}
}
if (terrainTypeTile.getCategory()
.equals(TerrainType.Category.Ocean)
|| terrainTypeTile.getCategory().equals(
TerrainType.Category.River)
|| terrainTypeTile.getCategory().equals(
TerrainType.Category.Hill)) {
non_countryTypes.add(new Integer(c));
}
}
TerrainRandomiser terrainRandomiser = new TerrainRandomiser(
countryTypes, non_countryTypes);
/*
* create vector to keep track of terrain randomisation 'clumping'
*/
Vector<RandomTerrainValue> locations = new Vector<RandomTerrainValue>();
for (int x = 0; x < mapRect.width; x++) {
pm.setValue(x);
for (int y = 0; y < mapRect.height; y++) {
int rgb = mapBufferedImage.getRGB(x, y);
FreerailsTile tile;
Integer type = rgb2TerrainType.get(rgb);
if (null == type) {
throw new NullPointerException(
"There is no terrain type mapped to rgb value "
+ rgb + " at location " + x + ", " + y);
}
tile = FreerailsTile.getInstance(terrainRandomiser
.getNewType(type.intValue()));
if (countryTypes.contains(tile.getTerrainTypeID())) {
locations.add(new RandomTerrainValue(x, y, tile
.getTerrainTypeID()));
}
w.setTile(x, y, tile);
}
}
for (int i = 0; i < locations.size(); i++) {
RandomTerrainValue rtv = locations.elementAt(i);
FreerailsTile tile = FreerailsTile.getInstance(rtv.getType());
int x = rtv.getX();
int y = rtv.getY();
int val = 3;
double prob = 0.75;
if (w.boundsContain(x - val, y - val)
&& w.boundsContain(x + val, y + val)) {
for (int m = x - val; m < x + val; m++) {
for (int n = y - val; n < y + val; n++) {
if (Math.random() > prob) {
setTile(m, n, tile);
}
}
}
}
}
}
private static void setTile(int x, int y, FreerailsTile tile) {
if (!non_countryTypes.contains(new Integer(((FreerailsTile) world
.getTile(x, y)).getTerrainTypeID()))) {
world.setTile(x, y, tile);
}
}
}
Methods:
MethodJavadoc
setTile
setupMap
jfreerails.server.MapFixtureFactory2
Javadoc:
/** * Stores a static world object and provides copies to clients. * * @author Luke Lindsay * */
Source code:
/**
* Stores a static world object and provides copies to clients.
*
* @author Luke Lindsay
*
*/
public class MapFixtureFactory2 {
private static World w;
/**
* Returns a world object with a map of size 50*50, 4 players, and track,
* terrain and cargo types as specified in the xml files used by the actual
* game.
*/
synchronized public static World getCopy() {
if (null == w) {
w = generateWorld();
}
return w.defensiveCopy();
}
private static World generateWorld() {
World world = new WorldImpl(50, 50);
TileSetFactory tileFactory = new TileSetFactoryImpl();
WagonAndEngineTypesFactory wetf = new WagonAndEngineTypesFactory();
wetf.addTypesToWorld(world);
tileFactory.addTerrainTileTypesList(world);
URL track_xml_url = OldWorldImpl.class
.getResource("/jfreerails/data/track_tiles.xml");
Track_TilesHandlerImpl trackSetFactory = new Track_TilesHandlerImpl(
track_xml_url);
trackSetFactory.addTrackRules(world);
// Add 4 players
for (int i = 0; i < 4; i++) {
String name = "player" + i;
Player p = new Player(name, i);
AddPlayerMove move = AddPlayerMove.generateMove(world, p);
MoveStatus ms = move.doMove(world, Player.AUTHORITATIVE);
assert(ms.ok);
}
world.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
world.setTime(new GameTime(0));
world.set(ITEM.GAME_SPEED, new GameSpeed(10));
world.set(ITEM.GAME_RULES, GameRules.DEFAULT_RULES);
int clearTypeID = 0;
// Fill the world with clear terrain.
for (int i = 0; i < world.size(SKEY.TERRAIN_TYPES); i++) {
TerrainType tt = (TerrainType) world.get(SKEY.TERRAIN_TYPES, i);
if ("Clear".equals(tt.getTerrainTypeName())) {
clearTypeID = i;
break;
}
}
FreerailsTile tile = FreerailsTile.getInstance(clearTypeID);
for (int x = 0; x < world.getMapWidth(); x++) {
for (int y = 0; y < world.getMapHeight(); y++) {
world.setTile(x, y, tile);
}
}
return world;
}
}
Methods:
MethodJavadoc
generateWorld
getCopy/**
jfreerails.server.OldWorldImpl
Javadoc:
/** * This class sets up a World object. * * @author luke */
Source code:
/**
* This class sets up a World object.
*
* @author luke
*/
public class OldWorldImpl {
/** Note, the map name is converted to lower case and any spaces
* are replaced with underscores.
*
*/
public static World createWorldFromMapFile(String mapName,
FreerailsProgressMonitor pm) {
mapName = mapName.toLowerCase();
mapName = mapName.replace(' ', '_');
pm.setValue(0);
pm.nextStep(7);
int progress = 0;
TileSetFactory tileFactory = new TileSetFactoryImpl();
pm.setValue(++progress);
WorldImpl w = new WorldImpl();
pm.setValue(++progress);
WagonAndEngineTypesFactory wetf = new WagonAndEngineTypesFactory();
pm.setValue(++progress);
wetf.addTypesToWorld(w);
pm.setValue(++progress);
tileFactory.addTerrainTileTypesList(w);
pm.setValue(++progress);
URL track_xml_url = OldWorldImpl.class
.getResource("/jfreerails/data/track_tiles.xml");
Track_TilesHandlerImpl trackSetFactory = new Track_TilesHandlerImpl(
track_xml_url);
pm.setValue(++progress);
trackSetFactory.addTrackRules(w);
pm.setValue(++progress);
// Load the terrain map
URL map_url = OldWorldImpl.class.getResource("/jfreerails/data/"
+ mapName + ".png");
MapFactory.setupMap(map_url, w, pm);
// Load the city names
URL cities_xml_url = OldWorldImpl.class.getResource("/jfreerails/data/"
+ mapName + "_cities.xml");
try {
InputCityNames.readCityNames(w, cities_xml_url);
} catch (SAXException e) {
}
// Randomly position the city tiles
CityTilePositioner ctp = new CityTilePositioner(w);
ctp.initCities();
// Set the time..
w.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
w.setTime(new GameTime(0));
w.set(ITEM.GAME_SPEED, new GameSpeed(10));
w.set(ITEM.GAME_RULES, GameRules.DEFAULT_RULES);
/*
* Note, money used to get added to player accounts here, now it is done
* when players are added. See AddPlayerMove
*/
return w;
}
}
Methods:
MethodJavadoc
createWorldFromMapFile/** Note, the map name is converted to lower case and any spaces
jfreerails.server.RandomTerrainValue
Javadoc:
/** * Stores a location and terrain type. * * @author Scott? */
Source code:
/**
* Stores a location and terrain type.
*
* @author Scott?
*/
public class RandomTerrainValue {
private final int x;
private final int y;
private final int terrainType;
public RandomTerrainValue(int x, int y, int tt) {
this.x = x;
this.y = y;
this.terrainType = tt;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getType() {
return terrainType;
}
}
Methods:
MethodJavadoc
getType
getX
getY
jfreerails.server.SavFileFilter
Javadoc:
/** * A SavedGamesManager reads and writes gzipped saved games to the working * directory. * * @author Luke * */
Source code:
/**
* A SavedGamesManager reads and writes gzipped saved games to the working
* directory.
*
* @author Luke
*
*/
class SavFileFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".sav"));
}
}
Methods:
MethodJavadoc
accept
jfreerails.server.SavedGamesManagerImpl
Javadoc:
/** * Manages saved games, providing methods to retrieve game names, save game states, load game states, and create new maps. * * @see SavedGamesManager * @see NewGameMessage2Server * @see SavFileFilter * @see ServerControl * @see OldWorldImpl * @see FreerailsProgressMonitor */
Source code:
public class SavedGamesManagerImpl implements SavedGamesManager {
private static final Logger logger = Logger
.getLogger(SavedGamesManagerImpl.class.getName());
public String[] getSaveGameNames() {
java.io.File dir = new File("./");
FilenameFilter filter = new SavFileFilter();
String[] files = dir.list(filter);
return files;
}
public String[] getNewMapNames() {
return NewGameMessage2Server.getMapNames();
}
public void saveGame(Serializable w, String s) throws IOException {
long startTime = System.currentTimeMillis();
logger.info("Saving game.. " + s);
FileOutputStream out = new FileOutputStream(s);
GZIPOutputStream zipout = new GZIPOutputStream(out);
ObjectOutputStream objectOut = new ObjectOutputStream(zipout);
objectOut.writeObject(ServerControlInterface.VERSION);
objectOut.writeObject(w);
objectOut.flush();
objectOut.close();
out.close();
long finishTime = System.currentTimeMillis();
long deltaTime = finishTime - startTime;
logger.info("done, " + deltaTime + "ms");
}
public Serializable loadGame(String name) throws IOException {
long startTime = System.currentTimeMillis();
logger.info("Loading game.. " + name);
FileInputStream in = new FileInputStream(name);
GZIPInputStream zipin = new GZIPInputStream(in);
ObjectInputStream objectIn = new ObjectInputStream(zipin);
String version_string;
try {
version_string = (String) objectIn.readObject();
if (!ServerControlInterface.VERSION.equals(version_string)) {
throw new IOException(version_string);
}
Serializable game = (Serializable) objectIn.readObject();
/**
* load player private data
*/
// for (int i = 0; i < world.getNumberOfPlayers(); i++) {
// Player player = world.getPlayer(i);
// player.loadSession(objectIn);
// }
long finishTime = System.currentTimeMillis();
long deltaTime = finishTime - startTime;
logger.info("done, " + deltaTime + "ms");
return game;
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IOException(e.getMessage());
} catch (InvalidClassException e) {
// e.printStackTrace();
throw new IOException(e.getMessage());
}
}
public Serializable newMap(String name) throws IOException {
return OldWorldImpl.createWorldFromMapFile(name,
FreerailsProgressMonitor.NULL_INSTANCE);
}
}
Methods:
MethodJavadoc
getNewMapNames
getSaveGameNames
loadGame
newMap
saveGame
jfreerails.server.ServerAutomaton
Javadoc:
/** * This interface is implemented by objects which are responsible for updating * the game world. They are serialized when the game is saved. They are internal * clients of the ServerGameEngine and need to be initialised with a connection * to the game when deserialized. * * @author rob */
Source code:
/**
* This interface is implemented by objects which are responsible for updating
* the game world. They are serialized when the game is saved. They are internal
* clients of the ServerGameEngine and need to be initialised with a connection
* to the game when deserialized.
*
* @author rob
*/
public interface ServerAutomaton extends Serializable {
/**
* Initializes the automaton with a connection to the MoveExecutor.
*/
public void initAutomaton(MoveReceiver mr);
}
Methods:
MethodJavadoc
initAutomaton/**
jfreerails.server.ServerGameModelImpl
Javadoc:
/** * A ServerGameModel that contains the automations used in the actual game. * * @author Luke * */
Source code:
/**
* A ServerGameModel that contains the automations used in the actual game.
*
* @author Luke
*
*/
public class ServerGameModelImpl implements ServerGameModel {
private static final long serialVersionUID = 3978144352788820021L;
public World world;
private transient CalcSupplyAtStations calcSupplyAtStations;
private TrainUpdater tb;
private String[] passwords;
/**
* List of the ServerAutomaton objects connected to this game.
*/
private final Vector<ServerAutomaton> serverAutomata;
/**
* Number of ticks since the last time we did an infrequent update.
*/
private int ticksSinceUpdate = 0;
private transient long nextModelUpdateDue;
private transient MoveReceiver moveExecuter;
public ServerGameModelImpl() {
this(null, new Vector<ServerAutomaton>());
}
public ServerGameModelImpl( World w,
Vector<ServerAutomaton> serverAutomata) {
this.world = w;
this.serverAutomata = serverAutomata;
nextModelUpdateDue = System.currentTimeMillis();
}
/** This is called on the last tick of each year. */
private void yearEnd() {
TrackMaintenanceMoveGenerator tmmg = new TrackMaintenanceMoveGenerator(
moveExecuter);
tmmg.update(world);
TrainMaintenanceMoveGenerator trainMaintenanceMoveGenerator = new TrainMaintenanceMoveGenerator(
moveExecuter);
trainMaintenanceMoveGenerator.update(world);
InterestChargeMoveGenerator interestChargeMoveGenerator = new InterestChargeMoveGenerator(
moveExecuter);
interestChargeMoveGenerator.update(world);
// Grow cities.
WorldDiffs wd = new WorldDiffs(world);
CityTilePositioner ctp = new CityTilePositioner(wd);
ctp.growCities();
WorldDiffMove move = new WorldDiffMove(world, wd, WorldDiffMove.Cause.YearEnd);
moveExecuter.processMove(move);
}
/** This is called at the start of each new month. */
private void monthEnd() {
calcSupplyAtStations.doProcessing();
CargoAtStationsGenerator cargoAtStationsGenerator = new CargoAtStationsGenerator();
cargoAtStationsGenerator.update(world, moveExecuter);
}
private void updateGameTime() {
moveExecuter.processMove(TimeTickMove.getMove(world));
}
/**
*
*/
public synchronized void update() {
long frameStartTime = System.currentTimeMillis();
while (nextModelUpdateDue <= frameStartTime) {
/*
* First do the things that need doing whether or not the game is
* paused.
*/
tb.buildTrains(world);
int gameSpeed = ((GameSpeed) world.get(ITEM.GAME_SPEED)).getSpeed();
if (gameSpeed > 0) {
/*
* Update the time first, since other updates might need to know
* the current time.
*/
updateGameTime();
// now do the other updates
tb.moveTrains(world);
// Check whether we are about to start a new year..
GameTime time = world.currentTime();
GameCalendar calendar = (GameCalendar) world.get(ITEM.CALENDAR);
int yearNextTick = calendar.getYear(time.getTicks() + 1);
int yearThisTick = calendar.getYear(time.getTicks());
if (yearThisTick != yearNextTick) {
yearEnd();
}
// And a new month..
int monthThisTick = calendar.getMonth(time.getTicks());
int monthNextTick = calendar.getMonth(time.getTicks() + 1);
if (monthNextTick != monthThisTick) {
monthEnd();
}
/* calculate "ideal world" time for next tick */
nextModelUpdateDue = nextModelUpdateDue + (1000 / gameSpeed);
// int delay = (int)(nextModelUpdateDue - frameStartTime);
//
// /* wake up any waiting client threads - we could be
// * more aggressive, and only notify them if delay > 0? */
// this.notifyAll();
//
// try {
// if (delay > 0) {
// this.wait(delay);
// } else {
// this.wait(1);
// }
// } catch (InterruptedException e) {
// // do nothing
// }
ticksSinceUpdate++;
} else {
// try {
// //When the game is frozen we don't want to be spinning in a
// //loop.
// Thread.sleep(200);
// } catch (InterruptedException e) {
// // do nothing
// }
nextModelUpdateDue = System.currentTimeMillis();
}
}
}
public void write(ObjectOutputStream objectOut) throws IOException {
objectOut.writeObject(world);
objectOut.writeObject(serverAutomata);
/**
* save player private data
*/
for (int i = 0; i < world.getNumberOfPlayers(); i++) {
Player player = world.getPlayer(i);
player.saveSession(objectOut);
}
}
public void init(MoveReceiver newMoveExecuter) {
this.moveExecuter = newMoveExecuter;
tb = new TrainUpdater(newMoveExecuter);
calcSupplyAtStations = new CalcSupplyAtStations(world, newMoveExecuter);
for (int i = 0; i < serverAutomata.size(); i++) {
serverAutomata.get(i).initAutomaton(newMoveExecuter);
}
tb.initAutomaton(newMoveExecuter);
nextModelUpdateDue = System.currentTimeMillis();
}
public World getWorld() {
return world;
}
public void setWorld(World w, String[] passwords) {
this.world = w;
this.serverAutomata.clear();
this.passwords = passwords.clone();
}
public String[] getPasswords() {
return passwords.clone();
}
}
Methods:
MethodJavadoc
getPasswords
getWorld
init
monthEnd/** This is called at the start of each new month. */
setWorld
update/**
updateGameTime
write
yearEnd/** This is called on the last tick of each year. */
jfreerails.server.TerrainRandomiser
Javadoc:
/** * Class to randomly select a terrain type for a terrain tile. * * TerrainRandomiser.java * * @author Scott Bennett Created on 23rd Jan 2004 The * Terrain Types are: 0) City (Urban) 1) Refinery (Industry) 2) Village * (Urban) 3) Factory (Industry) 4) Clear (Country) 5) Farm (Country) 6) * Desert (Country) 7) Ocean (Ocean) 8) Harbour (Ocean) 9) Stock-Yard * (Industry) 10) Food_Proc._Plant (Industry) 11) Cattle_Ranch * (Resource) 12) Grain_Elevator (Resource) 13) Oil_Well (Resource) 14) * Lumber_Mill (Resource) 15) Sugar_Plant. (Resource) 16) River (River) * 17) Landing (River) 18) Terminal (Special) 19) Jungle (Country) 20) * Hills (Hill) 21) Foothills (Hill) 22) Mountain (Hill) */
Source code:
/**
* Class to randomly select a terrain type for a terrain tile.
*
* TerrainRandomiser.java
*
* @author Scott Bennett Created on 23rd Jan 2004 The
* Terrain Types are: 0) City (Urban) 1) Refinery (Industry) 2) Village
* (Urban) 3) Factory (Industry) 4) Clear (Country) 5) Farm (Country) 6)
* Desert (Country) 7) Ocean (Ocean) 8) Harbour (Ocean) 9) Stock-Yard
* (Industry) 10) Food_Proc._Plant (Industry) 11) Cattle_Ranch
* (Resource) 12) Grain_Elevator (Resource) 13) Oil_Well (Resource) 14)
* Lumber_Mill (Resource) 15) Sugar_Plant. (Resource) 16) River (River)
* 17) Landing (River) 18) Terminal (Special) 19) Jungle (Country) 20)
* Hills (Hill) 21) Foothills (Hill) 22) Mountain (Hill)
*/
public class TerrainRandomiser {
private final Vector<Integer> terrainTypes;
private final Vector<Integer> non_terrainTypes;
private final double CLEAR_PERCENTAGE = 0.98; // ie. % of map that is
// clear (on avg.)
public TerrainRandomiser(Vector<Integer> num, Vector<Integer> num2) {
terrainTypes = num;
non_terrainTypes = num2;
}
public int getNewType(int type) {
int newType = type;
double value;
double divide = 1.0 / terrainTypes.size();
// allow any terrain type to be drawn over except those listed in
// non_terrainTypes
if (!non_terrainTypes.contains(new Integer(newType))) {
if (Math.random() < CLEAR_PERCENTAGE) {
// make the tile Clear
return 4;
}
value = Math.random();
/*
* at the moment, this logic produces a balanced and even
* distribution of the different country tiles (currently 3).
* somehow it would be better to have the actual proportions of
* Farms, Jungle and Desert etc vary. dunno how.
*/
for (int i = 0; i < terrainTypes.size(); i++) {
if ((value > (i * divide)) && (value <= ((i + 1) * divide))) {
return terrainTypes.elementAt(i).intValue();
}
}
}
return newType;
}
}
Methods:
MethodJavadoc
getNewType
jfreerails.server.TileSetFactoryImpl
Javadoc:
/** * This class adds cargo and terrain types defined in an XML file to a World * object. * * @author Luke * */
Source code:
/**
* This class adds cargo and terrain types defined in an XML file to a World
* object.
*
* @author Luke
*
*/
public class TileSetFactoryImpl implements TileSetFactory {
public void addTerrainTileTypesList(World w) {
try {
java.net.URL url = RunTypesParser.class
.getResource("/jfreerails/data/cargo_and_terrain.xml");
CargoAndTerrainParser.parse(url, new CargoAndTerrainHandlerImpl(w));
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException();
}
}
}
Methods:
MethodJavadoc
addTerrainTileTypesList
jfreerails.server.TrackMaintenanceMoveGenerator
Javadoc:
/** * This class iterates over the entries in the BankAccount and counts the number * of units of each track type, then calculates the cost of maintenance. * * @author Luke Lindsay * */
Source code:
/**
* This class iterates over the entries in the BankAccount and counts the number
* of units of each track type, then calculates the cost of maintenance.
*
* @author Luke Lindsay
*
*/
public class TrackMaintenanceMoveGenerator {
private final MoveReceiver moveReceiver;
public TrackMaintenanceMoveGenerator(MoveReceiver mr) {
this.moveReceiver = mr;
}
public static AddTransactionMove generateMove(World w,
FreerailsPrincipal principal, Transaction.Category category) {
if (TRACK_MAINTENANCE != category && STATION_MAINTENANCE != category) {
throw new IllegalArgumentException(String.valueOf(category));
}
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, principal);
aggregator.setCategory(TRACK);
long amount = 0;
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
long maintenanceCost = trackRule.getMaintenanceCost().getAmount();
// Is the track type the category we are interested in?
boolean rightType = TRACK_MAINTENANCE == category ? !trackRule
.isStation() : trackRule.isStation();
if (rightType) {
aggregator.setType(i);
amount += maintenanceCost * aggregator.calculateQuantity()
/ TrackConfiguration.LENGTH_OF_STRAIGHT_TRACK_PIECE;
}
}
Transaction t = new Bill(new Money(amount), category);
return new AddTransactionMove(principal, t);
}
public void update(World w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
Move m = generateMove(w, principal, TRACK_MAINTENANCE);
moveReceiver.processMove(m);
m = generateMove(w, principal, STATION_MAINTENANCE);
moveReceiver.processMove(m);
}
}
}
Methods:
MethodJavadoc
generateMove
update
jfreerails.server.TrainMaintenanceMoveGenerator
Javadoc:
/** * This class iterates over the entries in the BankAccount and counts the number * of trains, then calculates the cost of maintenance. * * @author Luke Lindsay * */
Source code:
/**
* This class iterates over the entries in the BankAccount and counts the number
* of trains, then calculates the cost of maintenance.
*
* @author Luke Lindsay
*
*/
public class TrainMaintenanceMoveGenerator {
private final MoveReceiver moveReceiver;
public TrainMaintenanceMoveGenerator(MoveReceiver mr) {
this.moveReceiver = mr;
}
private static AddTransactionMove generateMove(World w,
FreerailsPrincipal principal) {
NonNullElements trains = new NonNullElements(KEY.TRAINS, w, principal);
int numberOfTrains = trains.size();
long amount = numberOfTrains * 5000;
Transaction t = new Bill(new Money(amount),
Transaction.Category.TRAIN_MAINTENANCE);
return new AddTransactionMove(principal, t);
}
public void update(World w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
Move m = generateMove(w, principal);
moveReceiver.processMove(m);
}
}
}
Methods:
MethodJavadoc
generateMove
update
jfreerails.server.TrainPathFinder
Javadoc:
/** * This class provides methods that generate a path to a target as a series of * PositionOnTrack objects encoded as ints, it also deals with stops at * stations. * * @author Luke Lindsay 28-Nov-2002 */
Source code:
/**
* This class provides methods that generate a path to a target as a series of
* PositionOnTrack objects encoded as ints, it also deals with stops at
* stations.
*
* @author Luke Lindsay 28-Nov-2002
*/
public class TrainPathFinder implements FreerailsIntIterator, ServerAutomaton {
private static final long serialVersionUID = 3256446893302559280L;
private final SimpleAStarPathFinder pathFinder = new SimpleAStarPathFinder();
private final FreerailsPrincipal principal;
private final TrainStopsHandler stopsHandler;
private final FlatTrackExplorer trackExplorer;
private final int trainId;
private transient MoveReceiver mr = null;
ReadOnlyWorld w;
public TrainPathFinder(FlatTrackExplorer tx, ReadOnlyWorld w,
int trainNumber, MoveReceiver newMr, FreerailsPrincipal p) {
this.trackExplorer = tx;
this.trainId = trainNumber;
principal = p;
stopsHandler = new TrainStopsHandler(trainId, principal, new WorldDiffs(w));
this.mr = newMr;
this.w = w;
}
public boolean hasNextInt() {
boolean moving = stopsHandler.isTrainMoving();
if (moving) {
return trackExplorer.hasNextEdge();
}
mr.processMove(stopsHandler.getMoves());
return false;
}
public void initAutomaton(MoveReceiver newMr) {
this.mr = newMr;
}
boolean isTrainMoving() {
boolean moving = stopsHandler.isTrainMoving();
mr.processMove(stopsHandler.getMoves());
return moving;
}
/**
* @return a PositionOnTrack packed into an int
*/
public int nextInt() {
PositionOnTrack tempP = new PositionOnTrack(trackExplorer.getPosition());
int x = tempP.getX();
int y = tempP.getY();
ImPoint targetPoint = stopsHandler.arrivesAtPoint(x, y);
int currentPosition = tempP.getOpposite().toInt();
ReadOnlyWorld world = trackExplorer.getWorld();
PositionOnTrack[] t = FlatTrackExplorer.getPossiblePositions(world,
targetPoint);
int[] targets = new int[t.length];
for (int i = 0; i < t.length; i++) {
int target = t[i].getOpposite().toInt();
if (target == currentPosition) {
stopsHandler.updateTarget();
}
targets[i] = target;
}
FlatTrackExplorer tempExplorer = new FlatTrackExplorer(world, tempP);
int next = pathFinder.findstep(currentPosition, targets, tempExplorer);
if (next == IncrementalPathFinder.PATH_NOT_FOUND) {
trackExplorer.nextEdge();
trackExplorer.moveForward();
return trackExplorer.getVertexConnectedByEdge();
}
tempP.setValuesFromInt(next);
tempP = tempP.getOpposite();
int nextPosition = tempP.toInt();
trackExplorer.setPosition(nextPosition);
mr.processMove(stopsHandler.getMoves());
return nextPosition;
}
}
Methods:
MethodJavadoc
hasNextInt
initAutomaton
isTrainMoving
nextInt/**
jfreerails.server.TrainUpdater
Javadoc:
/** * This class is used by the server to generate moves that add trains, move * trains, and handle stops at stations. Note, the client should not use this * class to build trains, instead it should request that a train gets built by * setting production at an engine shop. * * @author Luke Lindsay 13-Oct-2002 * */
Source code:
/**
* This class is used by the server to generate moves that add trains, move
* trains, and handle stops at stations. Note, the client should not use this
* class to build trains, instead it should request that a train gets built by
* setting production at an engine shop.
*
* @author Luke Lindsay 13-Oct-2002
*
*/
public class TrainUpdater implements ServerAutomaton {
private static final long serialVersionUID = 3258410646839243577L;
/**
* @return a move that initialises the trains schedule.
*/
public static Move initTarget(TrainModel train, int trainID,
ImmutableSchedule currentSchedule, FreerailsPrincipal principal) {
Vector<Move> moves = new Vector<Move>();
int scheduleID = train.getScheduleID();
MutableSchedule schedule = new MutableSchedule(currentSchedule);
ImInts wagonsToAdd = schedule.getWagonsToAdd();
if (null != wagonsToAdd) {
int engine = train.getEngineType();
ChangeTrainMove move = ChangeTrainMove.generateMove(trainID, train,
engine, wagonsToAdd, principal);
moves.add(move);
}
schedule.gotoNextStation();
ImmutableSchedule newSchedule = schedule.toImmutableSchedule();
ChangeTrainScheduleMove move = new ChangeTrainScheduleMove(scheduleID,
currentSchedule, newSchedule, principal);
moves.add(move);
return new CompositeMove(moves.toArray(new Move[1]));
}
static TrainPositionOnMap setInitialTrainPosition(TrainModel train,
FreerailsPathIterator from) {
int trainLength = train.getLength();
PathWalker fromPathWalker = new PathWalkerImpl(from);
assert fromPathWalker.canStepForward();
fromPathWalker.stepForward(trainLength);
TrainPositionOnMap initialPosition = TrainPositionOnMap
.createInSameDirectionAsPath(fromPathWalker);
return initialPosition;
}
public static ImPoint[] trainPos2Tiles(TrainPositionOnMap pos) {
ImPoint[] returnValue = new ImPoint[pos.getLength()];
final int TILE_WIDTH = 30;
for (int i = 0; i < returnValue.length; i++) {
returnValue[i] = new ImPoint(pos.getX(i) / TILE_WIDTH, pos.getY(i)
/ TILE_WIDTH);
}
return returnValue;
}
private transient MoveReceiver moveReceiver;
public TrainUpdater(MoveReceiver mr) {
moveReceiver = mr;
if (null == mr) {
throw new NullPointerException();
}
}
public void buildTrain(int engineTypeId, ImInts wagons, ImPoint p,
FreerailsPrincipal principal, ReadOnlyWorld world) {
// If there are no wagons, setup an automatic schedule.
boolean autoSchedule = 0 == wagons.size();
ImmutableSchedule is = generateInitialSchedule(principal, world,
autoSchedule);
PreMove addTrain = new AddTrainPreMove(engineTypeId, wagons, p,
principal, is);
Move m = addTrain.generateMove(world);
moveReceiver.processMove(m);
}
// /**
// * Generates a composite move that adds a train to the train list, adds a
// * cargo bundle for the train to the cargo bundles list, and sets the
// * train's initial position. The move is sent to the moveProcessor and a
// * TrainMover object to update the trains position is returned.
// *
// * @param engineTypeId
// * type of the engine
// * @param wagons
// * array of wagon types
// * @param p
// * point at which to add train on map.
// *
// *
// */
// public TrainMover buildTrain(int engineTypeId, ImInts wagons, ImPoint p,
// FreerailsPrincipal principal, ReadOnlyWorld world) {
// /* Check that the specified position is on the track. */
// FreerailsTile tile = (FreerailsTile) world.getTile(p.x, p.y);
// if (NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER != tile.getTrackTypeID()) {
// /* Create the move that sets up the train's cargo bundle. */
// int cargoBundleId = world.size(principal, KEY.CARGO_BUNDLES);
// Move addCargoBundleMove = new AddCargoBundleMove(cargoBundleId,
// ImmutableCargoBundle.EMPTY_BUNDLE, principal);
//
// /* Create the train model object. */
// int scheduleId = world.size(principal, KEY.TRAIN_SCHEDULES);
//
// TrainModel train = new TrainModel(engineTypeId, wagons, scheduleId,
// cargoBundleId);
//
// /* Create the move that sets up the train's schedule. */
//
// // If there are no wagons, setup an automatic schedule.
// boolean autoSchedule = 0 == wagons.size();
//
// ImmutableSchedule is = generateInitialSchedule(principal, world,
// autoSchedule);
// int trainId = world.size(principal, KEY.TRAINS);
// Move setupScheduleMove = TrainUpdater.initTarget(train, trainId,
// is, principal);
//
// /* Create the move that sets the train's initial position. */
// FreerailsPathIterator from = getRandomPathToFollow(p, world);
// TrainPositionOnMap initialPosition = TrainUpdater
// .setInitialTrainPosition(train, from);
// Move positionMove = new InitialiseTrainPositionMove(trainId,
// initialPosition, principal);
//
// /* Determine the price of the train. */
// EngineType engineType = (EngineType) world.get(SKEY.ENGINE_TYPES,
// engineTypeId);
// Money price = engineType.getPrice();
//
// /* Create the move that adds the train to the train list. */
// AddTrainMove addTrainMove = AddTrainMove.generateMove(trainId,
// train, price, is, principal);
//
// /* Create a composite move made up of the moves created above. */
// Move compositeMove = new CompositeMove(new Move[] {
// addCargoBundleMove, addTrainMove, setupScheduleMove });
//
// /* Execute the move. */
// moveReceiver.processMove(compositeMove);
// moveReceiver.processMove(positionMove);
//
// /* Create a TrainMover to update the train's position. */
// TrainPathFinder tpf = getPathToFollow(p, world, trainId, principal);
// TrainMover trainMover = new TrainMover(tpf, world, trainId,
// principal);
//
// return trainMover;
// }
// throw new IllegalArgumentException("No track here (" + p.x + ", " + p.y
// + ") so cannot build train");
// }
/**
* Iterator over the stations and build trains at any that have their
* production field set.
*
*/
void buildTrains(ReadOnlyWorld world) {
for (int k = 0; k < world.getNumberOfPlayers(); k++) {
FreerailsPrincipal principal = world.getPlayer(k).getPrincipal();
for (int i = 0; i < world.size(principal, KEY.STATIONS); i++) {
StationModel station = (StationModel) world.get(principal,
KEY.STATIONS, i);
if (null != station) {
ImList<PlannedTrain> production = station
.getProduction();
if (production.size() > 0) {
ImPoint p = new ImPoint(station.x, station.y);
for (int j = 0; j < production.size(); j++) {
int engineType = production.get(j).getEngineType();
ImInts wagonTypes = production.get(j)
.getWagonTypes();
this.buildTrain(engineType, wagonTypes, p,
principal, world);
// TrainMover trainMover =
// this.buildTrain(engineType, wagonTypes, p,
// principal, world);
// this.addTrainMover(trainMover);
}
ChangeProductionAtEngineShopMove move = new ChangeProductionAtEngineShopMove(
production,
new ImList<PlannedTrain>(), i,
principal);
moveReceiver.processMove(move);
}
}
}
}
}
private ImmutableSchedule generateInitialSchedule(
FreerailsPrincipal principal, ReadOnlyWorld world,
boolean autoSchedule) {
WorldIterator wi = new NonNullElements(KEY.STATIONS, world, principal);
MutableSchedule s = new MutableSchedule();
// Add upto 4 stations to the schedule.
while (wi.next() && s.getNumOrders() < 5) {
TrainOrdersModel orders = new TrainOrdersModel(wi.getIndex(), null,
false, autoSchedule);
s.addOrder(orders);
}
s.setOrderToGoto(0);
ImmutableSchedule is = s.toImmutableSchedule();
return is;
}
public void initAutomaton(MoveReceiver mr) {
moveReceiver = mr;
}
void moveTrains(ReadOnlyWorld world) {
int time = world.currentTime().getTicks();
for (int k = 0; k < world.getNumberOfPlayers(); k++) {
FreerailsPrincipal principal = world.getPlayer(k).getPrincipal();
//If a train is moving, we want it to keep moving rather than stop
//to allow an already stationary train to start moving. To achieve this
//we process moving trains first.
ArrayList<Integer> movingTrains = new ArrayList<Integer>();
ArrayList<Integer> stoppedTrains = new ArrayList<Integer>();
for (int i = 0; i < world.size(principal, KEY.TRAINS); i++) {
TrainModel train = (TrainModel) world.get(principal,
KEY.TRAINS, i);
if (null == train) {
continue;
}
TrainAccessor ta = new TrainAccessor(world, principal, i);
if (ta.isMoving(time)) {
movingTrains.add(i);
} else {
stoppedTrains.add(i);
}
}
for (int trainId : movingTrains) {
moveTrain(world, principal, trainId);
}
for (int trainId : stoppedTrains) {
moveTrain(world, principal, trainId);
}
}
}
private void moveTrain(ReadOnlyWorld world, FreerailsPrincipal principal, int trainId) {
MoveTrainPreMove preMove = new MoveTrainPreMove(trainId, principal);
if (preMove.isUpdateDue(world)) {
TrainAccessor ta = new TrainAccessor(world, principal, trainId);
if (!ta.trackExists()) {
System.out.println("Track under train does not exist. Retiring train..");
this.retireTrain(world, principal, trainId);
} else {
Move m = preMove.generateMove(world);
moveReceiver.processMove(m);
}
}
}
private void retireTrain(ReadOnlyWorld world, FreerailsPrincipal principal, int trainId) {
Move m = RemoveTrainMove.getInstance(trainId, principal, world);
moveReceiver.processMove(m);
}
}
Methods:
MethodJavadoc
buildTrain
buildTrains/**
generateInitialSchedule
initAutomaton
initTarget/**
moveTrain
moveTrains
retireTrain
setInitialTrainPosition
trainPos2Tiles/**
jfreerails.server.common.TileSetFactory
Javadoc:
/** * This interface defines a method to add the terrain types to the world. * * @author Luke Lindsay 09 October 2001 */
Source code:
/**
* This interface defines a method to add the terrain types to the world.
*
* @author Luke Lindsay 09 October 2001
*/
public interface TileSetFactory {
void addTerrainTileTypesList(World w);
}
Methods:
MethodJavadoc
addTerrainTileTypesList
jfreerails.server.parser.CargoAndTerrainHandler
Javadoc:
/** * Defines methods to handle parsing the cargo and terrain types XML. * * @author Luke * @version generated by NetBeans XML module */
Source code:
/**
* Defines methods to handle parsing the cargo and terrain types XML.
*
* @author Luke
* @version generated by NetBeans XML module
*/
public interface CargoAndTerrainHandler {
/**
* An empty element event handling method.
*
*/
public void handle_Converts(final Attributes meta) throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/
public void start_Tile(final Attributes meta) throws SAXException;
/**
* A container element end event handling method.
*
*/
public void end_Tile() throws SAXException;
/**
* An empty element event handling method.
*
*/
public void handle_Cargo(final Attributes meta) throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/
public void start_Cargo_Types(final Attributes meta) throws SAXException;
/**
* A container element end event handling method.
*
*/
public void end_Cargo_Types() throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/
public void start_Terrain_Types(final Attributes meta) throws SAXException;
/**
* A container element end event handling method.
*
*/
public void end_Terrain_Types() throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/
public void start_Types(final Attributes meta) throws SAXException;
/**
* A container element end event handling method.
*
*/
public void end_Types() throws SAXException;
/**
* An empty element event handling method.
*
*/
public void handle_Consumes(final Attributes meta) throws SAXException;
/**
* An empty element event handling method.
*
*/
public void handle_Produces(final Attributes meta) throws SAXException;
}
Methods:
MethodJavadoc
end_Cargo_Types/**
end_Terrain_Types/**
end_Tile/**
end_Types/**
handle_Cargo/**
handle_Consumes/**
handle_Converts/**
handle_Produces/**
start_Cargo_Types/**
start_Terrain_Types/**
start_Tile/**
start_Types/**
jfreerails.server.parser.CargoAndTerrainHandlerImpl
Javadoc:
/** * Processes CargoAndTerrainHandler events and adds terrain and cargo types to * the world object. * * @see CargoAndTerrainHandler * @see CargoAndTerrainParser * @author Luke * @version generated by NetBeans XML module */
Source code:
/**
* Processes CargoAndTerrainHandler events and adds terrain and cargo types to
* the world object.
*
* @see CargoAndTerrainHandler
* @see CargoAndTerrainParser
* @author Luke
* @version generated by NetBeans XML module
*/
public class CargoAndTerrainHandlerImpl implements CargoAndTerrainHandler {
private final World world;
HashMap<String, Integer> cargoName2cargoTypeNumber = new HashMap<String, Integer>();
HashSet<Integer> rgbValuesAlreadyUsed = new HashSet<Integer>();
// Parsing variables for Tile
String tileID;
TerrainType.Category tileCategory;
int tileRGB;
int tileROW;
int tileBuildCost;
ArrayList<Consumption> typeConsumes = new ArrayList<Consumption>();
ArrayList<Production> typeProduces = new ArrayList<Production>();
ArrayList<Conversion> typeConverts = new ArrayList<Conversion>();
public CargoAndTerrainHandlerImpl(World w) {
world = w;
}
public void handle_Converts(final Attributes meta) throws SAXException {
String inputCargo = meta.getValue("input");
String outputCargo = meta.getValue("output");
int input = string2CargoID(inputCargo);
int output = string2CargoID(outputCargo);
Conversion conversion = new Conversion(input, output);
typeConverts.add(conversion);
}
public void start_Tile(final Attributes meta) throws SAXException {
typeConsumes.clear();
typeProduces.clear();
typeConverts.clear();
tileID = meta.getValue("id");
tileCategory = TerrainType.Category.valueOf(meta.getValue("Category"));
String rgbString = meta.getValue("rgb");
tileRGB = string2RGBValue(rgbString);
String buildCostString = meta.getValue("build_cost");
if (null != buildCostString) {
tileBuildCost = Integer.parseInt(buildCostString);
} else {
tileBuildCost = -1;
}
// Check if another type is already using this rgb value..
Integer rgbInteger = new Integer(tileRGB);
if (rgbValuesAlreadyUsed.contains(rgbInteger)) {
throw new SAXException(tileID + " can't using rgb value "
+ rgbString
+ " because it is being used by another tile type!");
}
rgbValuesAlreadyUsed.add(rgbInteger);
tileROW = Integer.parseInt(meta.getValue("right-of-way"));
}
public void end_Tile() throws SAXException {
Consumption[] consumes = new Consumption[typeConsumes.size()];
for (int i = 0; i < typeConsumes.size(); i++) {
consumes[i] = typeConsumes.get(i);
}
Production[] produces = new Production[typeProduces.size()];
for (int i = 0; i < typeProduces.size(); i++) {
produces[i] = typeProduces.get(i);
}
Conversion[] converts = new Conversion[typeConverts.size()];
for (int i = 0; i < typeConverts.size(); i++) {
converts[i] = typeConverts.get(i);
}
TileTypeImpl tileType = new TileTypeImpl(tileRGB, tileCategory, tileID,
tileROW, produces, consumes, converts, tileBuildCost);
world.add(SKEY.TERRAIN_TYPES, tileType);
}
public void handle_Cargo(final Attributes meta) throws SAXException {
String cargoID = meta.getValue("id");
String cargoCategory = meta.getValue("Category");
int unitWeight = Integer.parseInt(meta.getValue("unitWeight"));
CargoType cargoType = new CargoType(unitWeight, cargoID, Categories
.getCategory(cargoCategory));
int cargoNumber = world.size(SKEY.CARGO_TYPES);
cargoName2cargoTypeNumber.put(cargoID, new Integer(cargoNumber));
world.add(SKEY.CARGO_TYPES, cargoType);
}
public void start_Cargo_Types(final Attributes meta) throws SAXException {
// no need to do anything here.
}
public void end_Cargo_Types() throws SAXException {
// no need to do anything here.
}
public void start_Terrain_Types(final Attributes meta) throws SAXException {
// no need to do anything here.
}
public void end_Terrain_Types() throws SAXException {
// no need to do anything here.
}
public void start_Types(final Attributes meta) throws SAXException {
// no need to do anything here.
}
public void end_Types() throws SAXException {
// no need to do anything here.
}
public void handle_Consumes(final Attributes meta) throws SAXException {
int cargoConsumed = string2CargoID(meta.getValue("Cargo"));
String prerequisiteString = meta.getValue("Prerequisite");
// "Prerequisite" is an optional attribute, so may be null.
int prerequisiteForConsumption = (null == prerequisiteString ? 1
: Integer.parseInt(prerequisiteString));
Consumption consumption = new Consumption(cargoConsumed,
prerequisiteForConsumption);
typeConsumes.add(consumption);
}
public void handle_Produces(final Attributes meta) throws SAXException {
int cargoProduced = string2CargoID(meta.getValue("Cargo"));
int rateOfProduction = Integer.parseInt(meta.getValue("Rate"));
Production production = new Production(cargoProduced, rateOfProduction);
typeProduces.add(production);
}
private int string2RGBValue(String temp_number) {
int rgb = Integer.parseInt(temp_number, 16);
/*
* We need to change the format of the rgb value to the same one as used
* by the the BufferedImage that stores the map. See
* jfreerails.common.Map
*/
rgb = new java.awt.Color(rgb).getRGB();
return rgb;
}
/** Returns the index number of the cargo with the specified name. */
private int string2CargoID(String cargoName) throws SAXException {
if (cargoName2cargoTypeNumber.containsKey(cargoName)) {
Integer integer = cargoName2cargoTypeNumber.get(cargoName);
return integer.intValue();
}
throw new SAXException("Unknown cargo type: " + cargoName);
}
}
Methods:
MethodJavadoc
end_Cargo_Types
end_Terrain_Types
end_Tile
end_Types
handle_Cargo
handle_Consumes
handle_Converts
handle_Produces
start_Cargo_Types
start_Terrain_Types
start_Tile
start_Types/**
string2CargoID/** Returns the index number of the cargo with the specified name. */
string2RGBValue
jfreerails.server.parser.CargoAndTerrainParser
Javadoc:
/** * The class reads XML documents according to specified DTD and translates all * related events into CargoAndTerrainHandler events. * <p> * Usage sample: * * <pre> * RulesParser parser = new RulesParser(...); * parser.parse(new InputSource(&quot;...&quot;)); * </pre> * * <p> * <b>Warning:</b> the class is machine generated. DO NOT MODIFY * </p> * * @author Luke */
Source code:
/**
* The class reads XML documents according to specified DTD and translates all
* related events into CargoAndTerrainHandler events.
* <p>
* Usage sample:
*
* <pre>
* RulesParser parser = new RulesParser(...);
* parser.parse(new InputSource(&quot;...&quot;));
* </pre>
*
* <p>
* <b>Warning:</b> the class is machine generated. DO NOT MODIFY
* </p>
*
* @author Luke
*/
public class CargoAndTerrainParser implements ContentHandler {
private static final Logger logger = Logger
.getLogger(CargoAndTerrainParser.class.getName());
private java.lang.StringBuffer buffer;
private CargoAndTerrainHandler handler;
private java.util.Stack<Object[]> context;
private EntityResolver resolver;
/**
* Creates a parser instance.
*
* @param handler
* handler interface implementation (never <code>null</code>
* @param resolver
* SAX entity resolver implementation or <code>null</code>. It
* is recommended that it could be able to resolve at least the
* DTD.
*/
public CargoAndTerrainParser(final CargoAndTerrainHandler handler,
final EntityResolver resolver) {
this.handler = handler;
this.resolver = resolver;
buffer = new StringBuffer(111);
context = new java.util.Stack<Object[]>();
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void setDocumentLocator(Locator locator) {
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void startDocument() throws SAXException {
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void endDocument() throws SAXException {
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void startElement(java.lang.String ns, java.lang.String name,
java.lang.String qname, Attributes attrs) throws SAXException {
dispatch(true);
context.push(new Object[] { qname,
new org.xml.sax.helpers.AttributesImpl(attrs) });
if ("Converts".equals(name)) {
handler.handle_Converts(attrs);
} else if ("Tile".equals(name)) {
handler.start_Tile(attrs);
} else if ("Cargo".equals(name)) {
handler.handle_Cargo(attrs);
} else if ("Cargo_Types".equals(name)) {
handler.start_Cargo_Types(attrs);
} else if ("Terrain_Types".equals(name)) {
handler.start_Terrain_Types(attrs);
} else if ("Types".equals(name)) {
handler.start_Types(attrs);
} else if ("Consumes".equals(name)) {
handler.handle_Consumes(attrs);
} else if ("Produces".equals(name)) {
handler.handle_Produces(attrs);
}
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void endElement(java.lang.String ns, java.lang.String name,
java.lang.String qname) throws SAXException {
dispatch(false);
context.pop();
if ("Tile".equals(name)) {
handler.end_Tile();
} else if ("Cargo_Types".equals(name)) {
handler.end_Cargo_Types();
} else if ("Terrain_Types".equals(name)) {
handler.end_Terrain_Types();
} else if ("Types".equals(name)) {
handler.end_Types();
}
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void characters(char[] chars, int start, int len)
throws SAXException {
buffer.append(chars, start, len);
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void ignorableWhitespace(char[] chars, int start, int len)
throws SAXException {
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void processingInstruction(java.lang.String target,
java.lang.String data) throws SAXException {
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void startPrefixMapping(final java.lang.String prefix,
final java.lang.String uri) throws SAXException {
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void endPrefixMapping(final java.lang.String prefix)
throws SAXException {
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void skippedEntity(java.lang.String name) throws SAXException {
}
private void dispatch(final boolean fireOnlyIfMixed) throws SAXException {
if (fireOnlyIfMixed && buffer.length() == 0) {
return; // skip it
}
buffer.delete(0, buffer.length());
}
/**
* The recognizer entry method taking an Inputsource.
*
* @param input
* InputSource to be parsed.
* @throws java.io.IOException
* on I/O error.
* @throws SAXException
* propagated exception thrown by a DocumentHandler.
* @throws javax.xml.parsers.ParserConfigurationException
* a parser satisfying requested configuration can not be
* created.
*
*/
public static void parse(final InputSource input,
final CargoAndTerrainHandler handler) throws SAXException,
javax.xml.parsers.ParserConfigurationException, java.io.IOException {
parse(input, new CargoAndTerrainParser(handler, null));
}
/**
* The recognizer entry method taking a URL.
*
* @param url
* URL source to be parsed.
* @throws java.io.IOException
* on I/O error.
* @throws SAXException
* propagated exception thrown by a DocumentHandler.
* @throws javax.xml.parsers.ParserConfigurationException
* a parser satisfying requested configuration can not be
* created.
*
*/
public static void parse(final java.net.URL url,
final CargoAndTerrainHandler handler) throws SAXException,
javax.xml.parsers.ParserConfigurationException, java.io.IOException {
parse(new InputSource(url.toExternalForm()), handler);
}
private static void parse(final InputSource input,
final CargoAndTerrainParser recognizer) throws SAXException,
javax.xml.parsers.ParserConfigurationException, java.io.IOException {
javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory
.newInstance();
factory.setValidating(true); // the code was generated according DTD
factory.setNamespaceAware(true); // the code was generated according
// DTD
XMLReader parser = factory.newSAXParser().getXMLReader();
parser.setContentHandler(recognizer);
parser.setErrorHandler(recognizer.getDefaultErrorHandler());
if (recognizer.resolver != null) {
parser.setEntityResolver(recognizer.resolver);
}
parser.parse(input);
}
/**
* Creates default error handler used by this parser.
*
* @return org.xml.sax.ErrorHandler implementation
*
*/
protected ErrorHandler getDefaultErrorHandler() {
return new ErrorHandler() {
public void error(SAXParseException ex) throws SAXException {
if (context.isEmpty()) {
logger.severe("Missing DOCTYPE.");
}
throw ex;
}
public void fatalError(SAXParseException ex) throws SAXException {
throw ex;
}
public void warning(SAXParseException ex) throws SAXException {
// ignore
}
};
}
}
Methods:
MethodJavadoc
characters/**
dispatch
endDocument/**
endElement/**
endPrefixMapping/**
getDefaultErrorHandler/**
ignorableWhitespace/**
parse/**
parse/**
parse
processingInstruction/**
setDocumentLocator/**
skippedEntity/**
startDocument/**
startElement/**
startPrefixMapping/**
jfreerails.server.parser.RunTypesParser
Javadoc:
/** * The main method on this class uses CargoAndTerrainParser to the parse cargo * and terrain types xml file - use it to test the parser and xml file work * together. * * @author Luke */
Source code:
/**
* The main method on this class uses CargoAndTerrainParser to the parse cargo
* and terrain types xml file - use it to test the parser and xml file work
* together.
*
* @author Luke
*/
public class RunTypesParser {
private static final Logger logger = Logger.getLogger(RunTypesParser.class
.getName());
public static void main(String[] args) {
try {
java.net.URL url = RunTypesParser.class
.getResource("/jfreerails/data/cargo_and_terrain.xml");
CargoAndTerrainParser.parse(url, new CargoAndTerrainHandlerImpl(
new WorldImpl()));
logger.info("It worked");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Methods:
MethodJavadoc
main
jfreerails.server.parser.Track_TilesHandler
Javadoc:
/** * Defines methods to handle parsing the track types XML. * * @author lindsal * @version generated by FFJ XML module */
Source code:
/**
* Defines methods to handle parsing the track types XML.
*
* @author lindsal
* @version generated by FFJ XML module
*/
public interface Track_TilesHandler {
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_CanOnlyBuildOnTheseTerrainTypes(final Attributes meta)
throws SAXException;
/**
* A container element end event handling method.
*/
void end_CanOnlyBuildOnTheseTerrainTypes() throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_ListOfTrackPieceTemplates(final Attributes meta)
throws SAXException;
/**
* A container element end event handling method.
*/
void end_ListOfTrackPieceTemplates() throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_ListOfLegalRoutesAcrossNode(final Attributes meta)
throws SAXException;
/**
* A container element end event handling method.
*/
void end_ListOfLegalRoutesAcrossNode() throws SAXException;
/**
* An empty element event handling method.
*/
void handle_LegalRouteAcrossNode(final Attributes meta) throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_CannotBuildOnTheseTerrainTypes(final Attributes meta)
throws SAXException;
/**
* A container element end event handling method.
*/
void end_CannotBuildOnTheseTerrainTypes() throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_TrackType(final Attributes meta) throws SAXException;
/**
* A container element end event handling method.
*/
void end_TrackType() throws SAXException;
/**
* An empty element event handling method.
*/
void handle_TerrainType(final Attributes meta) throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_Tiles(final Attributes meta) throws SAXException;
/**
* A container element end event handling method.
*/
void end_Tiles() throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_TrackPieceTemplate(final Attributes meta) throws SAXException;
/**
* A container element end event handling method.
*/
void end_TrackPieceTemplate() throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_TrackSet(final Attributes meta) throws SAXException;
/**
* A container element end event handling method.
*/
void end_TrackSet() throws SAXException;
}
Methods:
MethodJavadoc
end_CanOnlyBuildOnTheseTerrainTypes/**
end_CannotBuildOnTheseTerrainTypes/**
end_ListOfLegalRoutesAcrossNode/**
end_ListOfTrackPieceTemplates/**
end_Tiles/**
end_TrackPieceTemplate/**
end_TrackSet/**
end_TrackType/**
handle_LegalRouteAcrossNode/**
handle_TerrainType/**
start_CanOnlyBuildOnTheseTerrainTypes/**
start_CannotBuildOnTheseTerrainTypes/**
start_ListOfLegalRoutesAcrossNode/**
start_ListOfTrackPieceTemplates/**
start_Tiles/**
start_TrackPieceTemplate/**
start_TrackSet/**
start_TrackType/**
jfreerails.server.parser.Track_TilesHandlerImpl
Javadoc:
/** * Processes Track_TilesHandle events, generates track rules, and provides a * methods to add the track rules to the world object. * * @author lindsal * @version generated by FFJ XML module * @see Track_TilesParser */
Source code:
/**
* Processes Track_TilesHandle events, generates track rules, and provides a
* methods to add the track rules to the world object.
*
* @author lindsal
* @version generated by FFJ XML module
* @see Track_TilesParser
*/
public class Track_TilesHandlerImpl implements Track_TilesHandler {
int maxConsequ;
protected List<TrackRule> ruleList;
protected jfreerails.world.track.TrackRuleProperties trackRuleProperties;
protected jfreerails.world.track.LegalTrackConfigurations legalTrackConfigurations;
protected ArrayList<String> legalTemplates;
protected HashSet<TerrainType.Category> terrainTypes;
protected LegalTrackPlacement legalTrackPlacement;
public void start_CanOnlyBuildOnTheseTerrainTypes(final Attributes meta)
throws SAXException {
terrainTypes = new HashSet<TerrainType.Category>();
}
public void end_CanOnlyBuildOnTheseTerrainTypes() throws SAXException {
legalTrackPlacement = new LegalTrackPlacement(terrainTypes,
LegalTrackPlacement.PlacementRule.ONLY_ON_THESE);
terrainTypes = null;
}
public void start_ListOfTrackPieceTemplates(final Attributes meta)
throws SAXException {
legalTemplates = new ArrayList<String>();
}
public void end_ListOfTrackPieceTemplates() throws SAXException {
legalTrackConfigurations = new jfreerails.world.track.LegalTrackConfigurations(
maxConsequ, legalTemplates);
legalTemplates = null;
}
public void start_ListOfLegalRoutesAcrossNode(final Attributes meta)
throws SAXException {
}
public void end_ListOfLegalRoutesAcrossNode() throws SAXException {
}
public void handle_LegalRouteAcrossNode(final Attributes meta)
throws SAXException {
}
public void start_CannotBuildOnTheseTerrainTypes(final Attributes meta)
throws SAXException {
terrainTypes = new java.util.HashSet<TerrainType.Category>();
}
public void end_CannotBuildOnTheseTerrainTypes() throws SAXException {
legalTrackPlacement = new LegalTrackPlacement(terrainTypes,
LegalTrackPlacement.PlacementRule.ANYWHERE_EXCEPT_ON_THESE);
terrainTypes = null;
}
public void start_TrackType(final Attributes meta) throws SAXException {
int rGBvalue;
String rgbString = meta.getValue("RGBvalue");
rGBvalue = Integer.parseInt(rgbString, 16);
/*
* We need to change the format of the rgb value to the same one as used
* by the the BufferedImage that stores the map. See
* jfreerails.common.Map
*/
rGBvalue = new java.awt.Color(rGBvalue).getRGB();
TrackRule.TrackCategories category = TrackRule.TrackCategories
.valueOf(meta.getValue("category"));
boolean enableDoubleTrack = Boolean.valueOf(
meta.getValue("doubleTrack")).booleanValue();
String typeName = meta.getValue("type");
maxConsequ = Integer.parseInt(meta.getValue("maxConsecuativePieces"));
String stationRadiusString = meta.getValue("stationRadius");
int stationRadius;
if (null != stationRadiusString) {
stationRadius = Integer.parseInt(stationRadiusString);
} else {
stationRadius = 0;
}
String priceString = meta.getValue("price");
int price = Integer.parseInt(priceString);
String fixedCostString = meta.getValue("fixedCost");
int fixedCost;
if (null != fixedCostString) {
fixedCost = Integer.parseInt(fixedCostString);
} else {
fixedCost = 0;
}
String maintenanceString = meta.getValue("maintenance");
int maintenance = Integer.parseInt(maintenanceString);
trackRuleProperties = new TrackRuleProperties(rGBvalue,
enableDoubleTrack, typeName, category, stationRadius, price,
maintenance, fixedCost);
}
public void end_TrackType() throws SAXException {
TrackRuleImpl trackRuleImpl = new jfreerails.world.track.TrackRuleImpl(
trackRuleProperties, legalTrackConfigurations,
legalTrackPlacement);
ruleList.add(trackRuleImpl);
legalTrackConfigurations = null;
trackRuleProperties = null;
legalTrackPlacement = null;
}
public void handle_TerrainType(final Attributes meta) throws SAXException {
TerrainType.Category cat = TerrainType.Category.valueOf(meta
.getValue("name"));
terrainTypes.add(cat);
}
public void start_Tiles(final Attributes meta) throws SAXException {
}
public void end_Tiles() throws SAXException {
// Sort the track tiles by category then price.
Collections.sort(ruleList);
}
public void start_TrackPieceTemplate(final Attributes meta)
throws SAXException {
legalTemplates.add(meta.getValue("trackTemplate"));
}
public void end_TrackPieceTemplate() throws SAXException {
// do nothing.
}
public void start_TrackSet(final Attributes meta) throws SAXException {
ruleList = new ArrayList<TrackRule>();
}
public void end_TrackSet() throws SAXException {
}
public Track_TilesHandlerImpl(java.net.URL trackXmlUrl) {
try {
Track_TilesParser.parse(trackXmlUrl, this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void addTrackRules(World w) {
for (int i = 0; i < this.ruleList.size(); i++) {
TrackRule r = ruleList.get(i);
w.add(SKEY.TRACK_RULES, r);
}
}
public List<TrackRule> getRuleList() {
return ruleList;
}
}
Methods:
MethodJavadoc
addTrackRules
end_CanOnlyBuildOnTheseTerrainTypes
end_CannotBuildOnTheseTerrainTypes
end_ListOfLegalRoutesAcrossNode
end_ListOfTrackPieceTemplates
end_Tiles
end_TrackPieceTemplate
end_TrackSet
end_TrackType
getRuleList
handle_LegalRouteAcrossNode
handle_TerrainType
start_CanOnlyBuildOnTheseTerrainTypes
start_CannotBuildOnTheseTerrainTypes
start_ListOfLegalRoutesAcrossNode
start_ListOfTrackPieceTemplates
start_Tiles
start_TrackPieceTemplate
start_TrackSet
start_TrackType
jfreerails.server.parser.Track_TilesParser
Javadoc:
/** * The class reads XML documents according to specified DTD and translates all * related events into Track_TilesHandler events. * <p> * Usage sample: * * <pre> * Track_TilesParser parser = new Track_TilesParser(...); * parser.parse(new InputSource(&quot;...&quot;)); * </pre> * * Date: 21 January 2002 18:00 * * @author lindsal * @version generated by FFJ XML module */
Source code:
/**
* The class reads XML documents according to specified DTD and translates all
* related events into Track_TilesHandler events.
* <p>
* Usage sample:
*
* <pre>
* Track_TilesParser parser = new Track_TilesParser(...);
* parser.parse(new InputSource(&quot;...&quot;));
* </pre>
*
* Date: 21 January 2002 18:00
*
* @author lindsal
* @version generated by FFJ XML module
*/
final public class Track_TilesParser implements org.xml.sax.ContentHandler {
private static final Logger logger = Logger
.getLogger(Track_TilesParser.class.getName());
private java.lang.StringBuffer buffer;
private Track_TilesHandler handler;
private java.util.Stack<Object[]> context;
public Track_TilesParser(final Track_TilesHandler handler) {
this.handler = handler;
buffer = new StringBuffer(111);
context = new java.util.Stack<Object[]>();
}
public void setDocumentLocator(org.xml.sax.Locator locator) {
}
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
public void startElement(java.lang.String ns, java.lang.String name,
java.lang.String qname, org.xml.sax.Attributes attrs)
throws SAXException {
dispatch(true);
context.push(new Object[] { qname,
new org.xml.sax.helpers.AttributesImpl(attrs) });
if ("CanOnlyBuildOnTheseTerrainTypes".equals(qname)) {
handler.start_CanOnlyBuildOnTheseTerrainTypes(attrs);
} else if ("ListOfTrackPieceTemplates".equals(qname)) {
handler.start_ListOfTrackPieceTemplates(attrs);
} else if ("ListOfLegalRoutesAcrossNode".equals(qname)) {
handler.start_ListOfLegalRoutesAcrossNode(attrs);
} else if ("LegalRouteAcrossNode".equals(qname)) {
handler.handle_LegalRouteAcrossNode(attrs);
} else if ("CannotBuildOnTheseTerrainTypes".equals(qname)) {
handler.start_CannotBuildOnTheseTerrainTypes(attrs);
} else if ("TrackType".equals(qname)) {
handler.start_TrackType(attrs);
} else if ("TerrainType".equals(qname)) {
handler.handle_TerrainType(attrs);
} else if ("Tiles".equals(qname)) {
handler.start_Tiles(attrs);
} else if ("TrackPieceTemplate".equals(qname)) {
handler.start_TrackPieceTemplate(attrs);
} else if ("TrackSet".equals(qname)) {
handler.start_TrackSet(attrs);
}
}
public void endElement(java.lang.String ns, java.lang.String name,
java.lang.String qname) throws SAXException {
dispatch(false);
context.pop();
if ("CanOnlyBuildOnTheseTerrainTypes".equals(qname)) {
handler.end_CanOnlyBuildOnTheseTerrainTypes();
} else if ("ListOfTrackPieceTemplates".equals(qname)) {
handler.end_ListOfTrackPieceTemplates();
} else if ("ListOfLegalRoutesAcrossNode".equals(qname)) {
handler.end_ListOfLegalRoutesAcrossNode();
} else if ("CannotBuildOnTheseTerrainTypes".equals(qname)) {
handler.end_CannotBuildOnTheseTerrainTypes();
} else if ("TrackType".equals(qname)) {
handler.end_TrackType();
} else if ("Tiles".equals(qname)) {
handler.end_Tiles();
} else if ("TrackPieceTemplate".equals(qname)) {
handler.end_TrackPieceTemplate();
} else if ("TrackSet".equals(qname)) {
handler.end_TrackSet();
}
}
public void characters(char[] chars, int start, int len)
throws SAXException {
buffer.append(chars, start, len);
}
public void ignorableWhitespace(char[] chars, int start, int len)
throws SAXException {
}
public void processingInstruction(java.lang.String target,
java.lang.String data) throws SAXException {
}
public void startPrefixMapping(final java.lang.String prefix,
final java.lang.String uri) throws SAXException {
}
public void endPrefixMapping(final java.lang.String prefix)
throws SAXException {
}
public void skippedEntity(java.lang.String name) throws SAXException {
}
private void dispatch(final boolean fireOnlyIfMixed) throws SAXException {
if (fireOnlyIfMixed && buffer.length() == 0) {
return; // skip it
}
buffer.delete(0, buffer.length());
}
/**
* The recognizer entry method taking an Inputsource.
*
* @param input
* InputSource to be parsed.
* @throws java.io.IOException
* on I/O error.
* @throws SAXException
* propagated exception thrown by a DocumentHandler.
* @throws javax.xml.parsers.ParserConfigurationException
* a parser satisfying requested configuration can not be
* created.
*/
public static void parse(final InputSource input,
final Track_TilesHandler handler) throws SAXException,
ParserConfigurationException, IOException {
parse(input, new Track_TilesParser(handler));
}
/**
* The recognizer entry method taking a URL.
*
* @param url
* URL source to be parsed.
* @throws java.io.IOException
* on I/O error.
* @throws SAXException
* propagated exception thrown by a DocumentHandler.
* @throws javax.xml.parsers.ParserConfigurationException
* a parser satisfying requested configuration can not be
* created.
*/
public static void parse(final java.net.URL url,
final Track_TilesHandler handler) throws SAXException,
ParserConfigurationException, IOException {
parse(new InputSource(url.toExternalForm()), handler);
}
private static void parse(final InputSource input,
final Track_TilesParser recognizer) throws SAXException,
ParserConfigurationException, IOException {
javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory
.newInstance();
factory.setValidating(true); // the code was generated according DTD
factory.setNamespaceAware(false); // the code was generated according
// DTD
org.xml.sax.XMLReader parser = factory.newSAXParser().getXMLReader();
parser.setContentHandler(recognizer);
parser.setErrorHandler(recognizer.getDefaultErrorHandler());
parser.parse(input);
}
private org.xml.sax.ErrorHandler getDefaultErrorHandler() {
return new org.xml.sax.ErrorHandler() {
public void error(org.xml.sax.SAXParseException ex)
throws SAXException {
if (context.isEmpty()) {
logger.severe("Missing DOCTYPE.");
}
throw ex;
}
public void fatalError(org.xml.sax.SAXParseException ex)
throws SAXException {
throw ex;
}
public void warning(org.xml.sax.SAXParseException ex)
throws SAXException {
// ignore
}
};
}
}
Methods:
MethodJavadoc
characters
dispatch
endDocument
endElement
endPrefixMapping
getDefaultErrorHandler
ignorableWhitespace
parse/**
parse/**
parse
processingInstruction
setDocumentLocator
skippedEntity/**
startDocument/**
startElement
startPrefixMapping
jfreerails.util.ArrayBase
Javadoc:
/** * Base class for type-specific growable array classes with any type of values * (including primitive types). This class builds on the basic structure * provided by <code>GrowableBase</code>, specializing it for usage as a * growable array. See the base class description for details of the * implementation. * <p> * * Growable arrays based on this class are not synchronized in order to provide * the best possible performance for typical usage scenarios, so explicit * synchronization must be implemented by the subclass or the application in * cases where they are to be modified in a multithreaded environment. * <p> * * Subclasses need to implement the abstract methods defined by the base class * for working with the data array, as well as the actual data access methods * (at least the basic <code>add()</code>, <code>get()</code>, * <code>set()</code>, and <code>toArray()</code> methods). * * @author Dennis M. Sosnoski * @version 1.0 */
Source code:
/**
* Base class for type-specific growable array classes with any type of values
* (including primitive types). This class builds on the basic structure
* provided by <code>GrowableBase</code>, specializing it for usage as a
* growable array. See the base class description for details of the
* implementation.
* <p>
*
* Growable arrays based on this class are not synchronized in order to provide
* the best possible performance for typical usage scenarios, so explicit
* synchronization must be implemented by the subclass or the application in
* cases where they are to be modified in a multithreaded environment.
* <p>
*
* Subclasses need to implement the abstract methods defined by the base class
* for working with the data array, as well as the actual data access methods
* (at least the basic <code>add()</code>, <code>get()</code>,
* <code>set()</code>, and <code>toArray()</code> methods).
*
* @author Dennis M. Sosnoski
* @version 1.0
*/
public abstract class ArrayBase extends GrowableBase implements Serializable {
/** The number of values currently present in the array. */
protected int countPresent;
/**
* Constructor with full specification.
*
* @param size
* number of elements initially allowed in array
* @param growth
* maximum size increment for growing array
* @param type
* array element type
*/
public ArrayBase(int size, int growth, Class type) {
super(size, growth, type);
}
/**
* Constructor with partial specification.
*
* @param size
* number of elements initially allowed in array
* @param type
* array element type
*/
public ArrayBase(int size, Class type) {
this(size, Integer.MAX_VALUE, type);
}
/**
* Copy (clone) constructor.
*
* @param base
* instance being copied
*/
public ArrayBase(ArrayBase base) {
super(base);
System.arraycopy(base.getArray(), 0, getArray(), 0, base.countPresent);
countPresent = base.countPresent;
}
/**
* Get the array for another instance of this class. This is a convenience
* method to allow subclasses access to the backing array of other
* subclasses.
*
* @param other
* subclass instance to get array from
* @return backing array object
*/
protected static Object getArray(ArrayBase other) {
return other.getArray();
}
/**
* Gets the array offset for appending a value to those in the array. If the
* underlying array is full, it is grown by the appropriate size increment
* so that the index value returned is always valid for the array in use by
* the time of the return.
*
* @return index position for added element
*/
protected final int getAddIndex() {
int index = countPresent++;
if (countPresent > countLimit) {
growArray(countPresent);
}
return index;
}
/**
* Makes room to insert a value at a specified index in the array.
*
* @param index
* index position at which to insert element
*/
protected void makeInsertSpace(int index) {
if (index >= 0 && index <= countPresent) {
if (++countPresent > countLimit) {
growArray(countPresent);
}
if (index < countPresent - 1) {
Object array = getArray();
System.arraycopy(array, index, array, index + 1, countPresent
- index - 1);
}
} else {
throw new ArrayIndexOutOfBoundsException("Invalid index value");
}
}
/**
* Remove a range of value from the array. The index positions for values
* above the range removed are decreased by the number of values removed.
*
* @param from
* index number of first value to be removed
* @param to
* index number past last value to be removed
*/
public void remove(int from, int to) {
if (from >= 0 && to <= countPresent && from <= to) {
if (to < countPresent) {
int change = from - to;
Object base = getArray();
System.arraycopy(base, to, base, from, countPresent - to);
discardValues(countPresent + change, countPresent);
countPresent += change;
}
} else {
throw new ArrayIndexOutOfBoundsException("Invalid remove range");
}
}
/**
* Remove a value from the array. All values above the index removed are
* moved down one index position.
*
* @param index
* index number of value to be removed
*/
public void remove(int index) {
remove(index, index + 1);
}
/**
* Get the number of values currently present in the array.
*
* @return count of values present
*/
public final int size() {
return countPresent;
}
/**
* Sets the number of values currently present in the array. If the new size
* is greater than the current size, the added values are initialized to the
* default values. If the new size is less than the current size, all values
* dropped from the array are discarded.
*
* @param count
* number of values to be set
*/
public void setSize(int count) {
if (count > countLimit) {
growArray(count);
} else if (count < countPresent) {
discardValues(count, countPresent);
}
countPresent = count;
}
/**
* Set the array to the empty state.
*/
public final void clear() {
setSize(0);
}
/**
* Constructs and returns a simple array containing the same data as held in
* a portion of this growable array. This override of the base class method
* checks that the portion specified actually has data present before
* constructing the returned array.
*
* @param type
* element type for constructed array
* @param offset
* start offset in array
* @param length
* number of characters to use
* @return array containing a copy of the data
*/
@Override
protected Object buildArray(Class type, int offset, int length) {
if (offset + length <= countPresent) {
return super.buildArray(type, offset, length);
}
throw new ArrayIndexOutOfBoundsException();
}
}
Methods:
MethodJavadoc
buildArray/**
clear/**
getAddIndex/**
getArray/**
makeInsertSpace/**
remove/**
remove/**
setSize/**
size/**
jfreerails.util.ClassLocater
Javadoc:
/** * An essential part of Java - locates any Class, anywhere. * <P> * This class should have been part of the JDK for the last 7 years, but Sun * hasn't added it, so we did it instead :). * <P> * No static methods since people are already using this in environments where * they need multiple separately configured copies running in parallel. Sun's * JVM design (caching classloaders) ensure that cached class data is * automatically shared between instances; it could be made faster by storing an * internal DB rather than re-instantiating, but the time-savings are minuscule * (might save some milliseconds if you have 1000 classes). * <p>Usage Tips</p> * If you are using this to automatically find all plugins that your users have * for your API then the easiest thing to do is declare a package that plugins * are in. Note: you could also declare a naming convention, as many open-source * projects have done when writing poor alternatives to this method. This is bad * practice, since java already has a naming-convention system - packages - and * we can easily use that - but it required more coding to make it work. There * are cases where you cannot use the packages this way (though personally I'd * recommend you re-think your design in that case), and in those cases you can * easily use a class-naming convention instead. So, everyone should be happy. * <P> * If you reserve a package for plugins, e.g. declare that all plugins must be * in package "org.javagamesfactory.plugins", then you simply pass something * like "org\.javagamesfactory\.plugins\..*" in (regex meaning "all things in * that package). This class will actually find all things in that package * <i>even if they are in different copies of that package, in different JAR * files, or different directories</i>. * <P> * To use a naming convention, e.g. all plugin class names start with the text * "PLUGIN" you would do something like: ".*\.PLUGIN.*". * <p> * In all cases, note the fact that regex's have special meaning for dot, so you * have to escape it when you just mean a full-stop. Read the java API docs for * java.util.regex for more information * * @see java.util.regex.Pattern */
Source code:
/**
* An essential part of Java - locates any Class, anywhere.
* <P> * This class should have been part of the JDK for the last 7 years, but Sun
* hasn't added it, so we did it instead :).
* <P>
* No static methods since people are already using this in environments where
* they need multiple separately configured copies running in parallel. Sun's
* JVM design (caching classloaders) ensure that cached class data is
* automatically shared between instances; it could be made faster by storing an
* internal DB rather than re-instantiating, but the time-savings are minuscule
* (might save some milliseconds if you have 1000 classes).
* <p>Usage Tips</p>
* If you are using this to automatically find all plugins that your users have
* for your API then the easiest thing to do is declare a package that plugins
* are in. Note: you could also declare a naming convention, as many open-source
* projects have done when writing poor alternatives to this method. This is bad
* practice, since java already has a naming-convention system - packages - and
* we can easily use that - but it required more coding to make it work. There
* are cases where you cannot use the packages this way (though personally I'd
* recommend you re-think your design in that case), and in those cases you can
* easily use a class-naming convention instead. So, everyone should be happy.
* <P>
* If you reserve a package for plugins, e.g. declare that all plugins must be
* in package "org.javagamesfactory.plugins", then you simply pass something
* like "org\.javagamesfactory\.plugins\..*" in (regex meaning "all things in
* that package). This class will actually find all things in that package
* <i>even if they are in different copies of that package, in different JAR
* files, or different directories</i>.
* <P>
* To use a naming convention, e.g. all plugin class names start with the text
* "PLUGIN" you would do something like: ".*\.PLUGIN.*".
* <p>
* In all cases, note the fact that regex's have special meaning for dot, so you
* have to escape it when you just mean a full-stop. Read the java API docs for
* java.util.regex for more information
*
* @see java.util.regex.Pattern
*/
public class ClassLocater {
protected static Logger logger = Logger.getLogger("jgf.classlocater");
protected LinkedList<String> skipPrefixes = new LinkedList<String>();
/**
* Finds all classes that implement or extend a given class name, and
* instantiates precisely one copy of each
*
* @param className
* fully qualified class or interface to find subclasses of, e.g.
* "java.lang.String"
* @param skipPrefixes
* prefixes of fully qualified packages or class names to
* completely ignore (i.e. not bother to check), making it
* faster, e.g. "java.", "com.sun"
* @return instantiated objects
*/
public static List instantiateOneOfEach(String className,
String[] skipPrefixes) {
Class[] classes = null;
LinkedList<Object> instances = new LinkedList<Object>();
try {
ClassLocater locater = new ClassLocater();
for (int i = 0; i < skipPrefixes.length; i++) {
locater.addSkipPrefix(skipPrefixes[i]);
}
classes = locater.getSubclassesOf(Class.forName(className));
logger.info("Found " + classes.length + " classes that implement "
+ className + "...");
if (logger.getLevel().equals(Level.FINE))
for (int i = 0; i < classes.length; i++) {
logger.fine("Found " + classes[i].getName()
+ " that implements " + className + "...");
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Attempting to find " + className
+ " implementers", e);
}
// Iterate through all, instantiating them
logger.fine("Instantiating each class");
for (int i = 0; i < classes.length; i++) {
try {
Object o = classes[i].newInstance();
instances.add(o);
} catch (Throwable e) {
logger.log(Level.SEVERE, "Failed to process: "
+ classes[i].getName(), e);
}
}
return instances;
}
/**
* Automatically adds sun's classes, the java library classes, and the
* Apache log4j classes (a lib used by ClassLocater!) to the skip list; it's
* very unlikely that you're trying to locate any of these!
*/
public ClassLocater() {
addSkipPrefix("org.apache.log4j.");
addSkipPrefix("com.sun.");
addSkipPrefix("java");
addSkipPrefix("junit");
}
/**
* Adds a prefix for classes (and packages) to completely ignore, based on
* their package + class name.
* <p>
* For example, "org.apache.log4j".
* <P>
* The advantage of this method is that you don't have to bother with regex
* syntax. Also, it is remembered between calls to getSubclassesOf - so it's
* useful if you know you never care about certain packages.
*
* @param s
* prefix of fully qualified class names to ignore
*/
public void addSkipPrefix(String s) {
skipPrefixes.add(s);
}
/**
* Find all instances of the given <code>Class</code> or interface by
* loading all classes on the class path.
* <P>
* Delegates to the other version, but passing in ".*" as the regex, i.e.
* "anything at all"
*
* @param targetType
* the superclass of all returned classes.
* @return an array of all subclasses of <code>targetType</code>
*/
public Class[] getSubclassesOf(Class targetType) {
return getSubclassesOf(targetType, ".*");
}
/**
* Find all subclasses of the given <code>Class</code> or interface by
* loading only those classes with names that match the given regular
* expression.
* <P>
* Once all classes have been checked, it will output at WARN a list of all
* the classes that were referenced by other classes but are not installed
* in the classpath. This can be incredibly useful - it catches situations
* where e.g. you thought a class was on the classpath but you put it in the
* wrong directory etc.
* <P>
* It can also be very annoying because java uses dynamic linking so it is
* LEGAL for many classes to be missing, just so long as you never use them
* at runtime. Because this class tries to use *every* class, it triggers
* errors on lots that you don't care about - use addSkipPrefix( class or
* package you dont use even though its on the classpath ) and they will be
* skipped (i.e. not even examined by this method).
* <P>
* OR improve your regex so that it is more selective about the packages
* where your classes could conceivable be located!
*
* @param targetType
* the superclass of all returned classes.
* @param regex
* a regular expression that will match with every subclass
* @return an array of all subclasses of <code>targetType</code>
*/
@SuppressWarnings("unchecked")
public Class[] getSubclassesOf(Class targetType, String regex) {
logger.info("Looking for all classes with names matching regex = "
+ regex + " and which are subtypes of " + targetType.getName());
StringBuffer sbSkips = new StringBuffer();
for (Iterator i2 = skipPrefixes.iterator(); i2.hasNext();) {
sbSkips.append(i2.next().toString() + "*");
if (i2.hasNext())
sbSkips.append(", ");
}
logger.info("...unless they match: " + sbSkips.toString());
LinkedList<Class> matches = new LinkedList<Class>();
HashMap<String, LinkedList<String>> missingRequiredClasses = new HashMap<String, LinkedList<String>>();
// maps class name to list of classes that needed it
logger.fine("Creating ClassPath object to do class search...");
ClassPath cp = new ClassPath();
logger.fine("Iterating through all classes in ClassPath...");
for (Iterator iter = cp.getAllClassNames().iterator(); iter.hasNext();) {
String className = (String) iter.next();
boolean skip = false;
for (Iterator i2 = skipPrefixes.iterator(); i2.hasNext();) {
String prefix = (String) i2.next();
if (className.startsWith(prefix)) {
logger.fine("Skipping class = " + className
+ " because it has a prefix of " + prefix);
skip = true;
break;
}
}
if (skip)
continue;
logger.fine("Processing class: " + className);
if (className.matches(regex)
&& !className.equals(targetType.getName())) {
logger
.fine("...matches regex; instantiating and checking type");
Class clazz = null;
try {
clazz = Class.forName(className);
}
/*
* catch (ClassNotFoundException cnfx ) { continue; }
*/
catch (NoClassDefFoundError cnfx) {
/*
* This is ridiculous. Please, everyone, ask sun to add a
* "getMissingClass()" method to NoClassDefFoundError: Sun,
* you have had TEN YEARS to fix this!
*/
if (cnfx.getMessage() == null) {
logger
.log(
Level.WARNING,
"NoClassDefFoundError but Sun didn't fill-in the message; no idea which class it was; ignoring it and moving on",
cnfx);
continue;
}
String missingClassName = cnfx.getMessage().replace('/',
'.');
LinkedList<String> misses = missingRequiredClasses
.get(missingClassName);
if (misses == null) {
misses = new LinkedList<String>();
missingRequiredClasses.put(missingClassName, misses);
}
misses.add(className);
continue;
} catch (UnsatisfiedLinkError cnfx) {
continue;
} catch (Throwable t) {
logger.log(Level.WARNING,
"Unexpected error - REMOVING this class ("
+ className + ") without checking it", t);
continue;
} finally {
if (clazz != null && targetType.isAssignableFrom(clazz)) {
logger
.fine(className
+ " matches and is correct type; adding to results");
matches.add(clazz);
}
}
}
}
if (missingRequiredClasses.size() > 0) {
logger
.warning("The following classes were needed by some of the classes I found, but could not themselves be found."
+ "Check you have the required libraries, that they are on the classpath, and that all JAR's are in your manifest as needed");
logger
.warning("If you don't care about some of the classes that used these missing classes, add the users to the skip list and you will get no errors from them");
for (Iterator<String> iter = missingRequiredClasses.keySet()
.iterator(); iter.hasNext();) {
String className = iter.next();
LinkedList<String> neededBy = missingRequiredClasses
.get(className);
StringBuffer sb = new StringBuffer();
for (Iterator<String> iterator = neededBy.iterator(); iterator
.hasNext();) {
String referencingClass = iterator.next();
sb.append(referencingClass);
if (iterator.hasNext())
sb.append(", ");
}
logger.warning("class: " + className + " was needed by class"
+ (neededBy.size() == 1 ? "" : "es") + ": " + sb);
}
}
logger.info("found " + matches.size() + " classes.");
return matches.toArray(new Class[matches.size()]);
}
}
Methods:
MethodJavadoc
addSkipPrefix/**
getSubclassesOf/**
getSubclassesOf/**
instantiateOneOfEach/**
jfreerails.util.ClassPath
Javadoc:
/** * ClassPath finds and records the fully qualified name of every Class on the * classpath via the system property "java.class.path". * <p> * Based on original prototype by duncanIdaho for javagaming.org. * * @author adam@jgf */
Source code:
/**
* ClassPath finds and records the fully qualified name of every Class on the
* classpath via the system property "java.class.path".
* <p>
* Based on original prototype by duncanIdaho for javagaming.org.
*
* @author adam@jgf
*/
public class ClassPath {
protected Logger logger = Logger.getLogger("jgf.classlocater.classpath");
protected LinkedList<String> pathElementsThatHaveAlreadyBeenProcessed;
protected LinkedList<File> jarsThatHAveAlreadyBeenProcessed;
/**
* create a new ClassPath instance and find all classes on the classpath
*/
public ClassPath() {
}
public List getAllClassNames() {
String path = null;
pathElementsThatHaveAlreadyBeenProcessed = new LinkedList<String>();
jarsThatHAveAlreadyBeenProcessed = new LinkedList<File>();
LinkedList<String> pendingClassPathElements = new LinkedList<String>();
LinkedList<String> processedClassPathElements = new LinkedList<String>();
try {
path = System.getProperty("java.class.path");
} catch (Exception x) {
x.printStackTrace();
}
logger.info("scanning classpath: " + path);
StringTokenizer toke = new StringTokenizer(path, File.pathSeparator);
while (toke.hasMoreTokens()) {
String pathElement = toke.nextToken();
pendingClassPathElements.add(pathElement);
}
for (Iterator<String> iter = pendingClassPathElements.iterator(); iter
.hasNext();) {
String pathElement = iter.next();
LinkedList<String> processPendingElement = processPendingElement(pathElement);
processedClassPathElements.addAll(processPendingElement);
}
return processedClassPathElements;
}
/**
* Clones the supplied list, then goes through it processing every element.
*
*/
protected LinkedList<String> processPendingElement(String pathElement) {
LinkedList<String> discoveredClasses = new LinkedList<String>();
File elementFile = new File(pathElement);
String elementName = elementFile.getAbsolutePath();
// do NOT process dupes
if (pathElementsThatHaveAlreadyBeenProcessed.contains(elementName))
return discoveredClasses;
try {
if (elementName.endsWith(".jar")) {
JarFile jar = null;
Manifest man = null;
jar = new JarFile(elementFile);
man = jar.getManifest();
// Find any nested path elements inside the JAR's own private
// class-path...
if (!(jarsThatHAveAlreadyBeenProcessed.contains(elementFile))) {
if (man != null) {
logger.fine("Jarfile = " + elementFile
+ " was not in jarsalreadydone (size = "
+ jarsThatHAveAlreadyBeenProcessed.size());
jarsThatHAveAlreadyBeenProcessed.add(elementFile);
List extraPathElements = findPathElementsInJar(man,
jar, elementFile);
logger.info("...[" + elementFile + "] contained "
+ extraPathElements.size()
+ " additional path elements");
for (Iterator iter = extraPathElements.iterator(); iter
.hasNext();) {
String element = (String) iter.next();
discoveredClasses
.addAll(processPendingElement(element));
}
}
// ...and add all the direct-listed classes that were in the
// JAR
Enumeration e = jar.entries();
while (e.hasMoreElements()) {
JarEntry entry = (JarEntry) e.nextElement();
if (!entry.isDirectory()
&& entry.getName().endsWith(".class")) {
String className = getClassNameFrom(entry.getName());
discoveredClasses.add(className);
}
}
}
} else if (elementName.endsWith(".zip")) {
discoveredClasses.addAll(getZipContents(elementFile));
} else if (elementName.endsWith(".class")) {
String className = convertToClass(elementFile);
discoveredClasses.add(className);
} else {
discoveredClasses.addAll(getDirectoryContents(elementFile));
}
// Mark this element as having been processed, and do NOT process
// dupes
pathElementsThatHaveAlreadyBeenProcessed.add(elementName);
} catch (Exception e) {
e.printStackTrace();
}
return discoveredClasses;
}
/**
* @param classFile
* a class file listed on the classpath itself.
*/
protected String convertToClass(File classFile) {
return getClassNameFrom(classFile.getName());
}
/**
* replace ANY slashes with dots and remove the .class at the end of the
* file name.
*
* @param entryName
* a file name relative to the classpath. A class of package org
* found in directory bin would be passed into this method as
* "org/MyClass.class"
* @return a fully qualified Class name.
*/
private String getClassNameFrom(String entryName) {
String foo = entryName.replace('/', '.');
foo = foo.replace('\\', '.');
return foo.substring(0, foo.lastIndexOf('.'));
}
/**
* Finds all path elements in the supplied JAR and returns them as a list
*
* @param man
* the manifest of the given jar
* @param jar
* the jar associated with the given manifest.
*/
protected LinkedList<String> findPathElementsInJar(Manifest man,
JarFile jar, File jarFile) {
LinkedList<String> result = new LinkedList<String>();
Attributes atts = man.getMainAttributes();
Set keys = atts.keySet();
Iterator i = keys.iterator();
while (i.hasNext()) {
Object key = i.next();
String value = (String) atts.get(key);
logger.fine(jar.getName() + " " + key + ": " + value);
if (key.toString().equals("Class-Path")) {
logger.info("scanning " + jar.getName()
+ "'s manifest classpath: " + value);
StringTokenizer toke = new StringTokenizer(value);
while (toke.hasMoreTokens()) {
String element = toke.nextToken();
if (jarFile.getParent() == null)
result.add(element);
else {
result.add(jarFile.getParent() + File.separator
+ element);
}
}
}
}
return result;
}
/**
* Adds all class names found in the zip mentioned
*
* @param zipFile
*/
protected LinkedList<String> getZipContents(File zipFile) {
LinkedList<String> result = new LinkedList<String>();
ZipFile zip = null;
try {
zip = new JarFile(zipFile);
} catch (IOException iox) {
}
if (zip != null) {
Enumeration e = zip.entries();
while (e.hasMoreElements()) {
ZipEntry entry = (ZipEntry) e.nextElement();
if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
String className = getClassNameFrom(entry.getName());
result.add(className);
}
}
}
return result;
}
/**
* This method takes a top level classpath dir i.e. 'classes' or bin
*
* @param dir
*/
protected LinkedList<String> getDirectoryContents(File dir) {
LinkedList<String> result = new LinkedList<String>();
// drill through contained dirs ... this is expected to be the
// 'classes' or 'bin' dir
File files[] = dir.listFiles();
if (null == files) {
logger.info("dir.listFiles() returned null for " + dir);
return result;
}
for (int i = 0; i < files.length; ++i) {
File f = files[i];
if (f.isDirectory()) {
result.addAll(getDirectoryContents("", f));
} else {
if (f.getName().endsWith(".class"))
result.add(convertToClass(f));
}
}
return result;
}
/**
* This method does the real directory recursion, passing along the the
* corresponding package-path to this directory.
*
* @param pathTo
* the preceding path to this directory
* @param dir
* a directory to search for class files
*/
protected LinkedList<String> getDirectoryContents(String pathTo, File dir) {
LinkedList<String> result = new LinkedList<String>();
String pathToHere = pathTo + dir.getName() + File.separator;
File files[] = dir.listFiles();
for (int i = 0; i < files.length; ++i) {
File f = files[i];
if (f.isDirectory()) {
result.addAll(getDirectoryContents(pathToHere, f));
} else {
if (f.getName().endsWith(".class")) {
String absFilePath = pathToHere + f.getName();
result.add(getClassNameFrom(absFilePath));
}
}
}
return result;
}
}
Methods:
MethodJavadoc
convertToClass/**
findPathElementsInJar/**
getAllClassNames
getClassNameFrom/**
getDirectoryContents/**
getDirectoryContents/**
getZipContents/**
processPendingElement/**
jfreerails.util.CompressedInputStream
Javadoc:
/** * A FilterInputStream for reading compressed data from a network connection. * * @author Patrice Espie Licensing: LGPL * @see CompressedOutputStream */
Source code:
/**
* A FilterInputStream for reading compressed data from a network connection.
*
* @author Patrice Espie Licensing: LGPL
* @see CompressedOutputStream
*/
public class CompressedInputStream extends FilterInputStream {
public CompressedInputStream(InputStream in) {
super(in);
buffer = new byte[0x7d000];
compBuffer = new byte[(int) (buffer.length * 1.2D)];
readIndex = 0;
maxReadIndex = 0;
inflater = new Inflater();
}
@Override
public boolean markSupported() {
return false;
}
@Override
public int available() throws IOException {
if (maxReadIndex - readIndex == 0 && super.in.available() > 0
&& !readNextBuffer()) {
return -1;
}
return maxReadIndex - readIndex;
}
@Override
public int read() throws IOException {
if (maxReadIndex - readIndex == 0 && !readNextBuffer()) {
return -1;
}
byte b = buffer[readIndex++];
if (b < 0) {
return 256 + b;
}
return b;
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (maxReadIndex - readIndex == 0 && !readNextBuffer()) {
return -1;
}
int read = 0;
for (int i = 0; i < len && available() > 0;) {
b[off + i] = (byte) read();
i++;
read++;
}
return read;
}
private boolean readNextBuffer() throws IOException {
byte compressionFlag = -1;
compressionFlag = (byte) super.in.read();
if (compressionFlag == -1) {
return false;
}
maxReadIndex = super.in.read() & 0xff;
maxReadIndex = maxReadIndex << 8 | super.in.read() & 0xff;
maxReadIndex = maxReadIndex << 8 | super.in.read() & 0xff;
maxReadIndex = maxReadIndex << 8 | super.in.read() & 0xff;
if (buffer.length < maxReadIndex) {
buffer = new byte[maxReadIndex + 40960];
}
if (compressionFlag == 1) {
int compSize = super.in.read() & 0xff;
compSize = compSize << 8 | super.in.read() & 0xff;
compSize = compSize << 8 | super.in.read() & 0xff;
compSize = compSize << 8 | super.in.read() & 0xff;
if (compBuffer.length < compSize) {
compBuffer = new byte[compSize + 40960];
}
for (int read = 0; read < compSize; read += super.in.read(
compBuffer, read, compSize - read)) {
}
inflater.reset();
inflater.setInput(compBuffer, 0, compSize);
try {
inflater.inflate(buffer);
} catch (DataFormatException ex) {
throw new IOException("Data format exception");
}
} else if (compressionFlag == 0) {
for (int read = 0; read < maxReadIndex; read += super.in.read(
buffer, read, maxReadIndex - read)) {
}
}
readIndex = 0;
return true;
}
private byte[] buffer;
private byte[] compBuffer;
private int readIndex;
private int maxReadIndex;
private Inflater inflater;
}
Methods:
MethodJavadoc
available
markSupported
read
read
read
readNextBuffer
jfreerails.util.CompressedOutputStream
Javadoc:
/** * A FilterOutputStream for sending compressed data over a network connection. * Note that standard ZipOutputStream and java.util.zip.GZipOutputStream don't * guarantee that flush sends out all the data written so far, which leads to * deadlocks in request-response-based protocols. * * @author Patrice Espie Licensing: LGPL */
Source code:
/**
* A FilterOutputStream for sending compressed data over a network connection.
* Note that standard ZipOutputStream and java.util.zip.GZipOutputStream don't
* guarantee that flush sends out all the data written so far, which leads to
* deadlocks in request-response-based protocols.
*
* @author Patrice Espie Licensing: LGPL
*/
public class CompressedOutputStream extends FilterOutputStream {
public CompressedOutputStream(OutputStream out) {
super(out);
buffer = new byte[0x7d000];
compBuffer = new byte[(int) (buffer.length * 1.2D)];
writeIndex = 0;
deflater = new Deflater(9);
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
int written = 0;
do {
if (written >= len) {
break;
}
int toWrite = Math.min(len - written, buffer.length - writeIndex);
System.arraycopy(b, off + written, buffer, writeIndex, toWrite);
written += toWrite;
writeIndex += toWrite;
if (writeIndex >= buffer.length * 0.80000000000000004D) {
flush();
}
} while (true);
}
@Override
public void write(int b) throws IOException {
if (writeIndex >= buffer.length * 0.80000000000000004D) {
flush();
}
buffer[writeIndex++] = (byte) b;
}
@Override
public void flush() throws IOException {
int compSize = 0;
boolean sendCompressed;
if (writeIndex > 150) {
deflater.reset();
deflater.setInput(buffer, 0, writeIndex);
deflater.finish();
if (compBuffer.length < writeIndex * 2 + 40960) {
compBuffer = new byte[writeIndex * 2 + 40960];
}
compSize = deflater.deflate(compBuffer);
if (compSize <= 0) {
throw new IOException("Compression exception");
}
sendCompressed = compSize < writeIndex;
} else {
sendCompressed = false;
}
if (sendCompressed) {
super.out.write(1);
super.out.write(writeIndex >> 24 & 0xff);
super.out.write(writeIndex >> 16 & 0xff);
super.out.write(writeIndex >> 8 & 0xff);
super.out.write(writeIndex & 0xff);
super.out.write(compSize >> 24 & 0xff);
super.out.write(compSize >> 16 & 0xff);
super.out.write(compSize >> 8 & 0xff);
super.out.write(compSize & 0xff);
super.out.write(compBuffer, 0, compSize);
super.out.flush();
writeIndex = 0;
} else if (writeIndex > 0) {
super.out.write(0);
super.out.write(writeIndex >> 24 & 0xff);
super.out.write(writeIndex >> 16 & 0xff);
super.out.write(writeIndex >> 8 & 0xff);
super.out.write(writeIndex & 0xff);
super.out.write(buffer, 0, writeIndex);
super.out.flush();
writeIndex = 0;
}
}
private byte[] buffer;
private byte[] compBuffer;
private int writeIndex;
private Deflater deflater;
}
Methods:
MethodJavadoc
flush
write
write
write
jfreerails.util.FlowRateInputStream
Javadoc:
/** * A FilterInputStream that measures flow rate. * * @author Patrice Espie Licensing: LGPL */
Source code:
/**
* A FilterInputStream that measures flow rate.
*
* @author Patrice Espie Licensing: LGPL
*/
public class FlowRateInputStream extends FilterInputStream implements Runnable {
private static final Logger logger = Logger
.getLogger(FlowRateInputStream.class.getName());
public FlowRateInputStream(InputStream in, String streamName) {
this(in, streamName, 60, 1000);
}
public FlowRateInputStream(InputStream in, String streamName,
int measureDuration, int measureInterval) {
super(in);
byteReceivedCumul = 0L;
totalByteReceived = 0L;
previousTotalByteReceived = 0L;
openTimeMillis = System.currentTimeMillis();
nextFree = 0;
nbUsed = 0;
running = false;
closeRequested = false;
byteReceived = new long[measureDuration];
this.measureInterval = measureInterval;
this.streamName = streamName;
if (this.measureInterval == 0) {
showTrace = false;
this.measureInterval = 1000L;
} else {
showTrace = true;
}
(new Thread(this)).start();
}
public FlowRateInputStream(InputStream in) {
this(in, "FlowRateInputStream", 60, 1000);
}
@Override
public void close() throws IOException {
closeRequested = true;
super.close();
do {
try {
Thread.currentThread();
Thread.sleep(50L);
} catch (InterruptedException interruptedexception) {
}
} while (running);
logger.info(String.valueOf(String.valueOf((new StringBuffer("Stream "))
.append(streamName).append(": Open duration = ").append(
(System.currentTimeMillis() - openTimeMillis) / 1000D)
.append(", Byte received = ").append(totalByteReceived).append(
" (").append((int) (totalByteReceived / 1024D)).append(
" Ko), overall flow rate = ").append(overallRate())
.append(" Ko/s"))));
}
@Override
public int read() throws IOException {
int r = super.in.read();
totalByteReceived += r;
return r;
}
@Override
public int read(byte[] b) throws IOException {
int r = super.in.read(b);
totalByteReceived += r;
return r;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int r = super.in.read(b, off, len);
totalByteReceived += r;
return r;
}
public int currentRate() {
return (int) (byteReceivedCumul / 1024D / (nbUsed * (measureInterval / 1000D)));
}
public String currentRateString() {
double d = (byteReceivedCumul / 1024D / (nbUsed * (measureInterval / 1000D)));
return decimalFormat.format(d);
}
public int overallRate() {
return (int) (totalByteReceived / 1024D / ((System.currentTimeMillis() - openTimeMillis) / 1000D));
}
public void run() {
if (running || measureInterval == 0x7fffffffffffffffL) {
return;
}
running = true;
try {
do {
try {
Thread.currentThread();
Thread.sleep(measureInterval);
} catch (InterruptedException interruptedexception) {
}
if (!closeRequested) {
long totalByteReceivedCopy = totalByteReceived;
long byteSentThisTime = totalByteReceivedCopy
- previousTotalByteReceived;
previousTotalByteReceived = totalByteReceivedCopy;
byteReceivedCumul -= byteReceived[nextFree];
byteReceived[nextFree] = byteSentThisTime;
byteReceivedCumul += byteSentThisTime;
nextFree = (nextFree + 1) % byteReceived.length;
nbUsed = Math.min(byteReceived.length, nbUsed + 1);
if (showTrace) {
logger
.info(String
.valueOf(String
.valueOf((new StringBuffer(
"Stream "))
.append(streamName)
.append(
": Open duration = ")
.append(
(System
.currentTimeMillis() - openTimeMillis) / 1000D)
.append(
", Byte sent = ")
.append(
totalByteReceived)
.append(" (")
.append(
(int) (totalByteReceived / 1024D))
.append(
" Ko), current flow rate = ")
.append(
currentRateString())
.append(" Ko/s"))));
}
}
} while (!closeRequested);
} finally {
running = false;
}
}
private long[] byteReceived;
private long byteReceivedCumul;
private long totalByteReceived;
private long previousTotalByteReceived;
private long openTimeMillis;
private long measureInterval;
private int nextFree;
private int nbUsed;
private boolean running;
private boolean closeRequested;
private String streamName;
private boolean showTrace;
private DecimalFormat decimalFormat = new DecimalFormat("0.00");
}
Methods:
MethodJavadoc
close
currentRate
currentRateString
overallRate
read
read
read
run
jfreerails.util.FlowRateOutputStream
Javadoc:
/** * A FilterOutputStream that measures flow rate. * * @author Patrice Espie Licensing: LGPL */
Source code:
/**
* A FilterOutputStream that measures flow rate.
*
* @author Patrice Espie Licensing: LGPL
*/
public class FlowRateOutputStream extends FilterOutputStream implements
Runnable {
private static final Logger logger = Logger
.getLogger(FlowRateOutputStream.class.getName());
public FlowRateOutputStream(OutputStream out, String streamName) {
this(out, streamName, 60, 1000);
}
public FlowRateOutputStream(OutputStream out, String streamName,
int measureDuration, int measureInterval) {
super(out);
byteSentCumul = 0L;
totalByteSent = 0L;
previousTotalByteSent = 0L;
openTimeMillis = System.currentTimeMillis();
nextFree = 0;
nbUsed = 0;
running = false;
closeRequested = false;
byteSent = new long[measureDuration];
this.measureInterval = measureInterval;
this.streamName = streamName;
if (this.measureInterval == 0) {
showTrace = false;
this.measureInterval = 1000L;
} else {
showTrace = true;
}
(new Thread(this)).start();
}
public FlowRateOutputStream(OutputStream out) {
this(out, "FlowRateOutputStream", 60, 1000);
}
@Override
public void close() throws IOException {
closeRequested = true;
super.close();
do {
try {
Thread.currentThread();
Thread.sleep(50L);
} catch (InterruptedException interruptedexception) {
}
} while (running);
logger.info(String.valueOf(String.valueOf((new StringBuffer("Stream "))
.append(streamName).append(": Open duration = ").append(
(System.currentTimeMillis() - openTimeMillis) / 1000D)
.append(", Byte sent = ").append(totalByteSent).append(" (")
.append((int) (totalByteSent / 1024D)).append(
" Ko), overall flow rate = ").append(
overallRateString()).append(" Ko/s"))));
}
@Override
public void write(byte[] b) throws IOException {
super.out.write(b, 0, b.length);
totalByteSent += b.length;
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
super.out.write(b, off, len);
totalByteSent += len;
}
@Override
public void write(int b) throws IOException {
super.out.write(b);
totalByteSent++;
}
public int currentRate() throws IOException {
return (int) (byteSentCumul / 1024D / (nbUsed * (measureInterval / 1000D)));
}
public int overallRate() throws IOException {
return (int) (totalByteSent / 1024D / ((System.currentTimeMillis() - openTimeMillis) / 1000D));
}
public String overallRateString() throws IOException {
double d = totalByteSent / 1024D
/ ((System.currentTimeMillis() - openTimeMillis) / 1000D);
return decimalFormat.format(d);
}
public String currentRateString() {
double d = (byteSentCumul / 1024D / (nbUsed * (measureInterval / 1000D)));
return decimalFormat.format(d);
}
public void run() {
if (running) {
throw new Error("Starting thread task on an already-started object");
}
if (measureInterval == 0x7fffffffffffffffL) {
return;
}
running = true;
try {
do {
try {
Thread.currentThread();
Thread.sleep(measureInterval);
} catch (InterruptedException interruptedexception) {
}
if (!closeRequested) {
long totalByteSentCopy = totalByteSent;
long byteSentThisTime = totalByteSentCopy
- previousTotalByteSent;
previousTotalByteSent = totalByteSentCopy;
byteSentCumul -= byteSent[nextFree];
byteSent[nextFree] = byteSentThisTime;
byteSentCumul += byteSentThisTime;
nextFree = (nextFree + 1) % byteSent.length;
nbUsed = Math.min(byteSent.length, nbUsed + 1);
if (showTrace) {
logger
.info(String
.valueOf(String
.valueOf((new StringBuffer(
"Stream "))
.append(streamName)
.append(
": Open duration = ")
.append(
(System
.currentTimeMillis() - openTimeMillis) / 1000D)
.append(
", Byte sent = ")
.append(totalByteSent)
.append(" (")
.append(
(int) (totalByteSent / 1024D))
.append(
" Ko), current flow rate = ")
.append(
currentRateString())
.append(" Ko/s"))));
}
}
} while (!closeRequested);
// } catch (IOException ioexception) {
} finally {
running = false;
}
}
private long[] byteSent;
private long byteSentCumul;
private long totalByteSent;
private long previousTotalByteSent;
private long openTimeMillis;
private long measureInterval;
private int nextFree;
private int nbUsed;
private boolean running;
private boolean closeRequested;
private String streamName;
private boolean showTrace;
private DecimalFormat decimalFormat = new DecimalFormat("0.00");
}
Methods:
MethodJavadoc
close
currentRate
currentRateString
overallRate
overallRateString
run
write
write
write
jfreerails.util.FreerailsIntIterator
Javadoc:
/** * Returns a series of ints. * * @author Luke Lindsay * */
Source code:
/**
* Returns a series of ints.
*
* @author Luke Lindsay
*
*/
public interface FreerailsIntIterator {
boolean hasNextInt();
int nextInt();
}
Methods:
MethodJavadoc
hasNextInt
nextInt
jfreerails.util.FreerailsProgressMonitor
Javadoc:
/** * This interface defines callbacks that can be used to let the user know how a * slow task is progressing. * * @author Luke Lindsay */
Source code:
/**
* This interface defines callbacks that can be used to let the user know how a
* slow task is progressing.
*
* @author Luke Lindsay
*/
public interface FreerailsProgressMonitor {
public static final FreerailsProgressMonitor NULL_INSTANCE = new FreerailsProgressMonitor() {
public void setValue(int i) {
}
public void nextStep(int max) {
}
public void finished() {
}
};
void setValue(int i);
void nextStep(int max);
void finished();
}
Methods:
MethodJavadoc
finished
nextStep
setValue
jfreerails.util.GameModel
Javadoc:
/** * Defines a standard method to update the game world. * * @author Luke * */
Source code:
/**
* Defines a standard method to update the game world.
*
* @author Luke
*
*/
public interface GameModel {
void update();
}
Methods:
MethodJavadoc
update
jfreerails.util.GrowableBase
Javadoc:
/** * Base class for various types of collections based on type-specific growable * arrays. The underlying array used for storage of items doubles in size each * time more space is required, up to an optional maximum growth increment * specified by the user. * * @author Dennis M. Sosnoski * @version 1.0 */
Source code:
/**
* Base class for various types of collections based on type-specific growable
* arrays. The underlying array used for storage of items doubles in size each
* time more space is required, up to an optional maximum growth increment
* specified by the user.
*
* @author Dennis M. Sosnoski
* @version 1.0
*/
public abstract class GrowableBase implements Serializable {
/** Default initial array size. */
public static final int DEFAULT_SIZE = 8;
/** Size of the current array. */
protected int countLimit;
/** Maximum size increment for growing array. */
protected int maximumGrowth;
/**
* Constructor with full specification.
*
* @param size
* number of elements in initial array
* @param growth
* maximum size increment for growing array
* @param type
* array element type
*/
public GrowableBase(int size, int growth, Class type) {
Object array = Array.newInstance(type, size);
countLimit = size;
maximumGrowth = growth;
setArray(array);
}
/**
* Constructor with partial specification.
*
* @param size
* number of elements initially allowed in array
* @param type
* array element type
*/
public GrowableBase(int size, Class type) {
this(size, Integer.MAX_VALUE, type);
}
/**
* Copy (clone) constructor.
*
* @param base
* instance being copied
*/
public GrowableBase(GrowableBase base) {
this(base.countLimit, base.maximumGrowth, base.getArray().getClass()
.getComponentType());
}
/**
* Get the backing array. This method is used by the type-agnostic base
* class code to access the array used for type-specific storage by the
* child class.
*
* @return backing array object
*/
protected abstract Object getArray();
/**
* Set the backing array. This method is used by the type-agnostic base
* class code to set the array used for type-specific storage by the child
* class.
*
*/
protected abstract void setArray(Object array);
/**
* Copy data after array resize. This default implementation just copies the
* entire contents of the old array to the start of the new array. It should
* be overridden in cases where data needs to be rearranged in the array
* after a resize.
*
* @param base
* original array containing data
* @param grown
* resized array for data
*/
protected void resizeCopy(Object base, Object grown) {
System.arraycopy(base, 0, grown, 0, Array.getLength(base));
}
/**
* Discards values for a range of indices in the array. Checks if the values
* stored in the array are object references, and if so clears them. If the
* values are primitives, this method does nothing.
*
* @param from
* index of first value to be discarded
* @param to
* index past last value to be discarded
*/
protected void discardValues(int from, int to) {
Object values = getArray();
if (!values.getClass().getComponentType().isPrimitive()) {
Object[] objects = (Object[]) values;
for (int i = from; i < to; i++) {
objects[i] = null;
}
}
}
/**
* Increase the size of the array to at least a specified size. The array
* will normally be at least doubled in size, but if a maximum size
* increment was specified in the constructor and the value is less than the
* current size of the array, the maximum increment will be used instead. If
* the requested size requires more than the default growth, the requested
* size overrides the normal growth and determines the size of the
* replacement array.
*
* @param required
* new minimum size required
*/
protected void growArray(int required) {
Object base = getArray();
int size = Math.max(required, countLimit
+ Math.min(countLimit, maximumGrowth));
Class type = base.getClass().getComponentType();
Object grown = Array.newInstance(type, size);
resizeCopy(base, grown);
countLimit = size;
setArray(grown);
}
/**
* Ensure that the array has the capacity for at least the specified number
* of values.
*
* @param min
* minimum capacity to be guaranteed
*/
public final void ensureCapacity(int min) {
if (min > countLimit) {
growArray(min);
}
}
/**
* Constructs and returns a simple array containing the same data as held in
* a portion of this growable array.
*
* @param type
* element type for constructed array
* @param offset
* start offset in array
* @param length
* number of characters to use
* @return array containing a copy of the data
*/
protected Object buildArray(Class type, int offset, int length) {
Object copy = Array.newInstance(type, length);
System.arraycopy(getArray(), offset, copy, 0, length);
return copy;
}
}
Methods:
MethodJavadoc
buildArray/**
discardValues/**
ensureCapacity/**
getArray/**
growArray/**
resizeCopy/**
setArray/**
jfreerails.util.Immutable
Javadoc:
/** * @author Luke 04-Jul-2005 */
Source code:
/**
* @author Luke 04-Jul-2005
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Immutable {
}
No methods in this class.
jfreerails.util.InstanceControlled
Javadoc:
/** * @author Luke 04-Jul-2005 */
Source code:
/**
* @author Luke 04-Jul-2005
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface InstanceControlled {
}
No methods in this class.
jfreerails.util.IntArray
Javadoc:
/** * Growable <code>int</code> array with type specific access methods. This * implementation is unsynchronized in order to provide the best possible * performance for typical usage scenarios, so explicit synchronization must be * implemented by a wrapper class or directly by the application in cases where * instances are modified in a multithreaded environment. See the base classes * for other details of the implementation. * * @author Dennis M. Sosnoski * @version 1.0 */
Source code:
/**
* Growable <code>int</code> array with type specific access methods. This
* implementation is unsynchronized in order to provide the best possible
* performance for typical usage scenarios, so explicit synchronization must be
* implemented by a wrapper class or directly by the application in cases where
* instances are modified in a multithreaded environment. See the base classes
* for other details of the implementation.
*
* @author Dennis M. Sosnoski
* @version 1.0
*/
public class IntArray extends ArrayBase implements Serializable {
private static final long serialVersionUID = 3258408426391418681L;
/** The underlying array used for storing the data. */
protected int[] baseArray;
/**
* Constructor with full specification.
*
* @param size
* number of <code>int</code> values initially allowed in array
* @param growth
* maximum size increment for growing array
*/
public IntArray(int size, int growth) {
super(size, growth, int.class);
}
/**
* Constructor with only initial size specified.
*
* @param size
* number of <code>int</code> values initially allowed in array
*/
public IntArray(int size) {
super(size, int.class);
}
/**
* Default constructor.
*/
public IntArray() {
this(DEFAULT_SIZE);
}
/**
* Copy (clone) constructor.
*
* @param base
* instance being copied
*/
public IntArray(IntArray base) {
super(base);
}
/**
* Get the backing array. This method is used by the type-agnostic base
* class code to access the array used for type-specific storage.
*
* @return backing array object
*/
@Override
protected final Object getArray() {
return baseArray;
}
/**
* Set the backing array. This method is used by the type-agnostic base
* class code to set the array used for type-specific storage.
*
*/
@Override
protected final void setArray(Object array) {
baseArray = (int[]) array;
}
/**
* Add a value to the array, appending it after the current values.
*
* @param value
* value to be added
* @return index number of added element
*/
public final int add(int value) {
int index = getAddIndex();
baseArray[index] = value;
return index;
}
/**
* Add a value at a specified index in the array.
*
* @param index
* index position at which to insert element
* @param value
* value to be inserted into array
*/
public void add(int index, int value) {
makeInsertSpace(index);
baseArray[index] = value;
}
/**
* Retrieve the value present at an index position in the array.
*
* @param index
* index position for value to be retrieved
* @return value from position in the array
*/
public final int get(int index) {
if (index < countPresent) {
return baseArray[index];
}
throw new ArrayIndexOutOfBoundsException("Invalid index value");
}
/**
* Set the value at an index position in the array.
*
* @param index
* index position to be set
* @param value
* value to be set
*/
public final void set(int index, int value) {
if (index < countPresent) {
baseArray[index] = value;
} else {
throw new ArrayIndexOutOfBoundsException("Invalid index value");
}
}
/**
* Constructs and returns a simple array containing the same data as held in
* this growable array.
*
* @return array containing a copy of the data
*/
public int[] toArray() {
return (int[]) buildArray(int.class, 0, countPresent);
}
/**
* Constructs and returns a simple array containing the same data as held in
* a portion of this growable array.
*
* @param offset
* start offset in array
* @param length
* number of characters to use
* @return array containing a copy of the data
*/
public int[] toArray(int offset, int length) {
return (int[]) buildArray(int.class, offset, length);
}
/**
* Duplicates the object with the generic call.
*
* @return a copy of the object
*/
@Override
public Object clone() {
return new IntArray(this);
}
}
Methods:
MethodJavadoc
add/**
add/**
get/**
getArray/**
set/**
setArray/**
toArray/**
toArray/**
jfreerails.util.LRUCache
Javadoc:
/** * An LRU cache, based on <code>LinkedHashMap</code>.<br> * This cache has a fixed maximum number of elements (<code>cacheSize</code>). * If the cache is full and another entry is added, the LRU (least recently * used) entry is dropped. * <p> * This class is thread-safe. All methods of this class are synchronized.<br> * Author: Christian d'Heureuse (<a * href="http://www.source-code.biz">www.source-code.biz</a>)<br> * License: <a href="http://www.gnu.org/licenses/lgpl.html">LGPL</a>. */
Source code:
/**
* An LRU cache, based on <code>LinkedHashMap</code>.<br>
* This cache has a fixed maximum number of elements (<code>cacheSize</code>).
* If the cache is full and another entry is added, the LRU (least recently
* used) entry is dropped.
* <p>
* This class is thread-safe. All methods of this class are synchronized.<br>
* Author: Christian d'Heureuse (<a
* href="http://www.source-code.biz">www.source-code.biz</a>)<br>
* License: <a href="http://www.gnu.org/licenses/lgpl.html">LGPL</a>.
*/
public class LRUCache<K, V> {
private static final float hashTableLoadFactor = 0.75f;
private LinkedHashMap<K, V> map;
private int cacheSize;
/**
* Creates a new LRU cache.
*
* @param cacheSize
* the maximum number of entries that will be kept in this cache.
*/
public LRUCache(int cacheSize) {
this.cacheSize = cacheSize;
int hashTableCapacity = (int) Math
.ceil(cacheSize / hashTableLoadFactor) + 1;
map = new LinkedHashMap<K, V>(hashTableCapacity, hashTableLoadFactor,
true) {
// (an anonymous inner class)
private static final long serialVersionUID = 1;
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > LRUCache.this.cacheSize;
}
};
}
/**
* Retrieves an entry from the cache.<br>
* The retrieved entry becomes the MRU (most recently used) entry.
*
* @param key
* the key whose associated value is to be returned.
* @return the value associated to this key, or null if no value with this
* key exists in the cache.
*/
public synchronized V get(K key) {
return map.get(key);
}
/**
* Adds an entry to this cache. If the cache is full, the LRU (least
* recently used) entry is dropped.
*
* @param key
* the key with which the specified value is to be associated.
* @param value
* a value to be associated with the specified key.
*/
public synchronized void put(K key, V value) {
map.put(key, value);
}
/**
* Clears the cache.
*/
public synchronized void clear() {
map.clear();
}
/**
* Returns the number of used entries in the cache.
*
* @return the number of entries currently in the cache.
*/
public synchronized int usedEntries() {
return map.size();
}
/**
* Returns a <code>Collection</code> that contains a copy of all cache
* entries.
*
* @return a <code>Collection</code> with a copy of the cache content.
*/
public synchronized Collection<Map.Entry<K, V>> getAll() {
return new ArrayList<Map.Entry<K, V>>(map.entrySet());
}
} // end class LRUCache
Methods:
MethodJavadoc
clear/**
get/**
getAll/**
put/**
usedEntries/**
jfreerails.util.List1D
Javadoc:
/** * Represents a one-dimensional list of elements of type T. * This interface provides methods to manage the list, including adding, removing, * accessing, and modifying elements. * * @since 1.0 * @see java.util.List */
Source code:
public interface List1D<T> extends Serializable {
int size();
T get(int i);
T removeLast();
int add(T element);
void set(int i, T element);
}
Methods:
MethodJavadoc
add
get
removeLast
set
size
jfreerails.util.List1DDiff
Javadoc:
/** * <strong>List1DDiff</strong> provides a 1-dimensional list diff view, allowing modification of an underlying list while tracking changes. * This class delegates most operations to the superclass {@link ListXDDiffs} but overrides methods to ensure 1D indexing and behavior. * It wraps an underlying {@link List1D} instance, exposing its elements through diff-aware access. * * @author YourName * @since 1.0 * @see ListXDDiffs * @see List1D */
Source code:
public class List1DDiff<T> extends ListXDDiffs<T> implements List1D<T> {
private static final long serialVersionUID = -6058018396890452219L;
private final List1D<T> underlyingList;
public List1DDiff(SortedMap<ListKey, Object> diffs, List1D<T> list,
Enum listID) {
super(diffs, listID);
underlyingList = list;
}
public T get(int i) {
return get(new int[] { i });
}
@Override
Object getUnderlyingList() {
return underlyingList;
}
public int size() {
return super.size(new int[0]);
}
@Override
T uGet(int... i) {
if (i.length != 1)
throw new IllegalArgumentException();
return underlyingList.get(i[0]);
}
public int add(T element) {
return super.addElement(element);
}
public T removeLast() {
return super.removeLast();
}
public void set(int i, T element) {
super.set(element, i);
}
@Override
int getUnderlyingSize(int... dim) {
if (dim.length != 0)
throw new IllegalArgumentException(String.valueOf(dim.length));
return underlyingList.size();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof List1D))
return false;
return Lists.equals(this, (List1D) obj);
}
@Override
public int hashCode() {
return size();
}
}
Methods:
MethodJavadoc
add
get
getUnderlyingList
getUnderlyingSize
removeLast
set
size
uGet
jfreerails.util.List1DImpl
Javadoc:
/** * A concrete implementation of the List1D interface, providing a one-dimensional list * with standard operations such as add, remove, get, and set. This implementation uses * an ArrayList to store elements and provides basic list functionality. * * @see List1D * @see java.util.ArrayList */
Source code:
public class List1DImpl<T> implements List1D<T> {
private static final long serialVersionUID = 8285123045287237133L;
private final ArrayList<T> elementData;
public List1DImpl() {
elementData = new ArrayList<T>();
}
public List1DImpl(int initialSize) {
elementData = new ArrayList<T>();
for (int i = 0; i < initialSize; i++) {
elementData.add(null);
}
}
public int size() {
return elementData.size();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof List1D))
return false;
return Lists.equals(this, (List1D) obj);
}
@Override
public int hashCode() {
return size();
}
public T get(int i) {
return elementData.get(i);
}
public T removeLast() {
int last = elementData.size() - 1;
return elementData.remove(last);
}
public int add(T element) {
elementData.add(element);
return elementData.size() - 1;
}
public void set(int i, T element) {
elementData.set(i, element);
}
}
Methods:
MethodJavadoc
add
get
removeLast
set
size
jfreerails.util.List2D
Javadoc:
/** * A two-dimensional list interface that supports dynamic resizing and element manipulation. * This interface provides methods to manage elements in a 2D structure, allowing for * operations such as adding, removing, and retrieving elements along both dimensions. * * @author Your Name * @since 1.0 * @see java.util.List */
Source code:
public interface List2D<T> extends Serializable {
int sizeD1();
int sizeD2(int d1);
T get(int d1, int d2);
T removeLastD2(int d1);
int removeLastD1();
int addD1();
int addD2(int d1, T element);
void set(int d1, int d2, T element);
}
Methods:
MethodJavadoc
addD1
addD2
get
removeLastD1
removeLastD2
set
sizeD1
sizeD2
jfreerails.util.List2DDiff
Javadoc:
/** * Represents a two-dimensional list that tracks differences (diffs) between its current state and an underlying list. * This class provides methods to manipulate and inspect the list while delegating operations to the superclass for diff tracking. * It wraps a {@link List2D} instance and exposes its structure through diff-aware methods. * * @author Generated Documentation * @see ListXDDiffs * @see List2D * @see Lists */
Source code:
public class List2DDiff<T> extends ListXDDiffs<T> implements List2D<T> {
private final List2D<T> underlyingList;
public List2DDiff(SortedMap<ListKey, Object> diffs, List2D<T> list,
Enum listID) {
super(diffs, listID);
underlyingList = list;
}
private static final long serialVersionUID = 4323585276281406244L;
public int sizeD1() {
return super.size();
}
public int sizeD2(int d1) {
return super.size(d1);
}
public T get(int d1, int d2) {
return super.get(d1, d2);
}
public T removeLastD2(int d1) {
return super.removeLast(d1);
}
public int removeLastD1() {
return super.removeLastList();
}
public int addD1() {
return super.addDimension();
}
public int addD2(int d1, T element) {
return super.addElement(element, d1);
}
public void set(int d1, int d2, T element) {
super.set(element, d1, d2);
}
@Override
Object getUnderlyingList() {
return underlyingList;
}
@Override
T uGet(int... i) {
if (i.length != 2)
throw new IllegalArgumentException(String.valueOf(i.length));
return underlyingList.get(i[0], i[1]);
}
@Override
int getUnderlyingSize(int... dim) {
if(dim.length == 0)
return underlyingList.sizeD1();
if(dim.length == 1){
if (underlyingList.sizeD1() <= dim[0])
return -1;
return underlyingList.sizeD2(dim[0]);
}
throw new IllegalArgumentException(String.valueOf(dim.length));
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof List2D))
return false;
return Lists.equals(this, (List2D)obj);
}
@Override
public int hashCode() {
return sizeD1();
}
}
Methods:
MethodJavadoc
addD1
addD2
get
getUnderlyingList
getUnderlyingSize
removeLastD1
removeLastD2
set
sizeD1
sizeD2/**
uGet
jfreerails.util.List2DImpl
Javadoc:
/** * Implementation of the List2D interface providing a two-dimensional list structure. * This class manages a list of lists, allowing operations on both dimensions (d1 and d2). * It supports adding, removing, and accessing elements, as well as equality checks and hash code generation. * * @author [Author Name] * @since 1.0 * * @see List2D * @see java.util.ArrayList */
Source code:
public class List2DImpl<T> implements List2D<T> {
private static final long serialVersionUID = 7614246212629595959L;
private final ArrayList<ArrayList<T>> elementData = new ArrayList<ArrayList<T>>();
public List2DImpl(int d1){
for(int i = 0; i < d1; i++){
elementData.add(new ArrayList<T>());
}
}
public int sizeD1() {
return elementData.size();
}
public int sizeD2(int d1) {
return elementData.get(d1).size();
}
public T get(int d1, int d2) {
return elementData.get(d1).get(d2);
}
public T removeLastD2(int d1) {
int last = elementData.get(d1).size() -1;
T element = elementData.get(d1).get(last);
elementData.get(d1).remove(last);
return element;
}
public int removeLastD1() {
int last = elementData.size() -1;
if(sizeD2(last) != 0)
throw new IllegalStateException(String.valueOf(last));
elementData.remove(last);
return last;
}
public int addD1() {
elementData.add(new ArrayList<T>());
return elementData.size() -1;
}
public int addD2(int d1, T element) {
ArrayList<T> d2 = elementData.get(d1);
int index = d2.size();
d2.add(element);
return index;
}
public void set(int d1, int d2, T element) {
elementData.get(d1).set(d2, element);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof List2D)) {
return false;
}
return Lists.equals(this, (List2D)obj);
}
@Override
public int hashCode() {
return sizeD1();
}
}
Methods:
MethodJavadoc
addD1
addD2
get
removeLastD1
removeLastD2
set
sizeD1
sizeD2
jfreerails.util.List3D
Javadoc:
/** * A 3D list interface that provides methods for managing and accessing elements in three dimensions. * This interface extends {@link java.io.Serializable} to support serialization of 3D list instances. * It includes operations for retrieving sizes, accessing elements, and modifying the structure along each dimension. * * @see java.io.Serializable */
Source code:
public interface List3D<T> extends Serializable {
int sizeD1();
int sizeD2(int d1);
int sizeD3(int d1, int d2);
T get(int d1, int d2, int d3);
List<T> get(int d1, int d2);
T removeLastD3(int d1, int d2);
void removeLastD1();
void removeLastD2(int d1);
int addD1();
int addD2(int d1);
int addD3(int d1, int d2, T element);
void set(int d1, int d2, int d3, T element);
}
Methods:
MethodJavadoc
addD1
addD2
addD3
get/**
get
removeLastD1
removeLastD2
removeLastD3
set
sizeD1
sizeD2
sizeD3
jfreerails.util.List3DDiff
Javadoc:
/** * Represents a 3-dimensional list diff, providing a delta view of changes to a 3D list structure. * This class delegates operations to its superclass {@link ListXDDiffs} while exposing the underlying * 3D list via {@link #getUnderlyingList()}. It supports dimension manipulation, element access, * and size queries for multi-dimensional indexing. * * @author [Author Name] * @see ListXDDiffs * @see List3D * @see Lists */
Source code:
public class List3DDiff<T> extends ListXDDiffs<T> implements List3D<T> {
private static final long serialVersionUID = 14976913635251766L;
private final List3D<T> underlyingList;
public List3DDiff(SortedMap<ListKey, Object> diffs, List3D<T> list,
Enum listID) {
super(diffs, listID);
this.underlyingList = list;
}
public int addD1() {
return super.addDimension();
}
public int addD2(int d1) {
return super.addDimension(d1);
}
public int addD3(int d1, int d2, T element) {
return super.addElement(element, d1, d2);
}
public T get(int d1, int d2, int d3) {
return super.get(d1, d2, d3);
}
@Override
Object getUnderlyingList() {
return underlyingList;
}
@Override
int getUnderlyingSize(int... dim) {
if(dim.length == 0)
return underlyingList.sizeD1();
if(dim.length == 1){
if (underlyingList.sizeD1() <= dim[0])
return -1;
return underlyingList.sizeD2(dim[0]);
}
if(dim.length == 2){
if (underlyingList.sizeD1() <= dim[0])
return -1;
if (underlyingList.sizeD2(dim[0]) <= dim[1])
return -1;
return underlyingList.sizeD3(dim[0], dim[1]);
}
throw new IllegalArgumentException(String.valueOf(dim.length));
}
public void removeLastD1() {
super.removeLastList();
}
public void removeLastD2(int d1) {
super.removeLastList(d1);
}
public T removeLastD3(int d1, int d2) {
return super.removeLast(d1, d2);
}
public void set(int d1, int d2, int d3, T element) {
super.set(element, d1, d2, d3);
}
public int sizeD1() {
return super.size();
}
public int sizeD2(int d1) {
return super.size(d1);
}
public int sizeD3(int d1, int d2) {
return super.size(d1, d2);
}
@Override
T uGet(int... i) {
if (i.length != 3)
throw new IllegalArgumentException();
return underlyingList.get(i[0], i[1], i[2]);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof List3D))
return false;
return Lists.equals(this, (List3D)obj);
}
@Override
public int hashCode() {
return sizeD1();
}
public List<T> get(int d1, int d2) {
List<T> list = new ArrayList<T>();
for(int d3 = 0; d3 < sizeD3(d1, d2); d3++) {
list.add(get(d1, d2, d3));
}
return list;
}
}
Methods:
MethodJavadoc
addD1
addD2
addD3
get
get
getUnderlyingList
getUnderlyingSize
removeLastD1
removeLastD2
removeLastD3
set
sizeD1
sizeD2
sizeD3
uGet
jfreerails.util.List3DImpl
Javadoc:
/** * A 3D list implementation that manages elements in three dimensions. * This class provides methods to add, remove, and access elements in a 3D structure. * * @author Your Name * @since 1.0 * @see List3D */
Source code:
public class List3DImpl<T> implements List3D<T> {
private static final long serialVersionUID = 1353309875727204066L;
private ArrayList<ArrayList<ArrayList<T>>> elementData= new ArrayList<ArrayList<ArrayList<T>>>();
public List3DImpl(int d1, int d2){
for (int i = 0; i < d1; i++) {
ArrayList<ArrayList<T>> dim2 = new ArrayList<ArrayList<T>>();
elementData.add(dim2);
for (int j = 0; j < d2; j++) {
dim2.add(new ArrayList<T>() );
}
}
}
public int sizeD1() {
return elementData.size();
}
public int sizeD2(int d1) {
return elementData.get(d1).size();
}
public int sizeD3(int d1, int d2) {
return elementData.get(d1).get(d2).size();
}
public T get(int d1, int d2, int d3) {
return elementData.get(d1).get(d2).get(d3);
}
public T removeLastD3(int d1, int d2) {
ArrayList<T> dim3 = elementData.get(d1).get(d2);
int last = dim3.size()-1;
T element = dim3.get(last);
dim3.remove(last);
return element;
}
public void removeLastD1() {
int last = elementData.size()-1;
if(elementData.get(last).size() > 0)
throw new IllegalStateException(String.valueOf(last));
elementData.remove(last);
}
public void removeLastD2(int d1) {
ArrayList<ArrayList<T>> dim2 = elementData.get(d1);
int last = dim2.size()-1;
ArrayList<T> dim3 = dim2.get(last);
if(dim3.size() > 0)
throw new IllegalStateException(String.valueOf(d1));
dim2.remove(last);
}
public int addD1() {
ArrayList<ArrayList<T>> dim2 = new ArrayList<ArrayList<T>>();
elementData.add(dim2);
return elementData.size() -1;
}
public int addD2(int d1) {
ArrayList<ArrayList<T>> dim2 = elementData.get(d1);
dim2.add(new ArrayList<T>() );
return dim2.size()-1;
}
public int addD3(int d1, int d2, T element) {
ArrayList<T> dim3 = elementData.get(d1).get(d2);
dim3.add(element);
return dim3.size()-1;
}
public void set(int d1, int d2, int d3, T element) {
ArrayList<T> dim3 = elementData.get(d1).get(d2);
dim3.set(d3, element);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof List3D))
return false;
return Lists.equals(this, (List3D)obj);
}
@Override
public int hashCode() {
return sizeD1();
}
public List<T> get(int d1, int d2) {
return elementData.get(d1).get(d2);
}
}
Methods:
MethodJavadoc
addD1
addD2
addD3
get
get
removeLastD1
removeLastD2
removeLastD3
set
sizeD1
sizeD2
sizeD3
jfreerails.util.ListKey
Javadoc:
/** * <strong>ListKey</strong> represents a composite key used to uniquely identify and order elements in a list structure. * It encapsulates a type (Element or EndPoint), a list identifier (Enum), and an array of indices, providing methods for * equality checks, ordering, and string representation. This class is designed to be used as a key in collections requiring * precise comparison and serialization capabilities. * * @author [Author Name] * @since 1.0 * @see java.util.Enum * @see java.lang.Comparable * @see java.io.Serializable */
Source code:
public class ListKey implements Comparable<ListKey>, Serializable{
private static final long serialVersionUID = -4939641035786937927L;
public enum Type {
Element, EndPoint
}
private final Type type;
private final int[] index;
private final Enum listID;
public ListKey(Type t, Enum listID, int... i){
type = t;
index = i.clone();
this.listID = listID;
}
public int[] getIndex() {
return index.clone();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ListKey))
return false;
final ListKey listKey = (ListKey) o;
if (!Arrays.equals(index, listKey.index))
return false;
if (!listID.equals(listKey.listID))
return false;
if (!type.equals(listKey.type))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = type.hashCode();
result = 29 * result + listID.hashCode();
return result;
}
public Type getType() {
return type;
}
public int compareTo(ListKey o) {
if(o.listID != listID)
return o.listID.ordinal() - listID.ordinal();
if(index.length != o.index.length)
return index.length -o.index.length;
for (int i = 0; i < index.length; i++) {
if(index[i] != o.index[i])
return index[i] -o.index[i];
}
if(o.type != type)
return o.type.ordinal() - type.ordinal();
return 0;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(listID);
sb.append(" ");
sb.append(type);
sb.append(" index ");
for (int i = 0; i < index.length; i++) {
sb.append("[");
sb.append(index[i]);
sb.append("]");
}
return sb.toString();
}
public Enum getListID() {
return listID;
}
}
Methods:
MethodJavadoc
compareTo
getIndex
getListID
getType
jfreerails.util.ListXDDiffs
Javadoc:
/** * Manages and tracks differences in a multi-dimensional list structure, providing methods to add, remove, and retrieve elements while maintaining diff information for comparison or versioning purposes. * This abstract class serves as a base for implementing list diff tracking mechanisms, encapsulating operations to modify the list and persist changes in a {@link SortedMap} of {@link ListKey} entries. * * @author YourName * @since 1.0 * * @see ListKey * @see SortedMap * @see Serializable */
Source code:
public abstract class ListXDDiffs<T> implements Serializable {
private static final long serialVersionUID = 127789045793369316L;
static int[] add2Array(int[] dim, int last) {
int[] array = new int[dim.length + 1];
for (int i = 0; i < dim.length; i++) {
array[i] = dim[i];
}
array[array.length - 1] = last;
return array;
}
static int[] removeFromArray(int[] dim) {
int[] array = new int[dim.length - 1];
for (int i = 0; i < dim.length - 1; i++) {
array[i] = dim[i];
}
return array;
}
private final SortedMap<ListKey, Object> diffs;
private final Enum listID;
public ListXDDiffs(SortedMap<ListKey, Object> diffs, Enum listID) {
this.diffs = diffs;
this.listID = listID;
}
public int addDimension(int... dim) {
int i = size(dim);
ListKey sizeKeyA = new ListKey(ListKey.Type.EndPoint, listID, dim);
int[] subArray = add2Array(dim, i);
ListKey sizeKeyB = new ListKey(ListKey.Type.EndPoint, listID, subArray);
diffs.put(sizeKeyA, new Integer(i + 1));
diffs.put(sizeKeyB, new Integer(0));
return i;
}
public int addElement(T element, int... dim) {
int sizeBefore = size(dim);
int[] index = add2Array(dim, sizeBefore);
setElementDiff: {
if (getUnderlyingSize(dim) > sizeBefore) {
T uElement = uGet(index);
if (Utils.equal(uElement, element)) {
// We are reading an element that was removed, in which
// case we don't store a diff.
break setElementDiff;
}
}
ListKey elementKey = new ListKey(ListKey.Type.Element, listID,
index);
diffs.put(elementKey, element);
}
setSize(sizeBefore + 1, dim);
return sizeBefore;
}
@SuppressWarnings("unchecked")
public T get(int... i) {
checkBounds(i);
ListKey elementKey = new ListKey(ListKey.Type.Element, listID, i);
if (diffs.containsKey(elementKey)) {
return (T) diffs.get(elementKey);
}
return uGet(i);
}
abstract Object getUnderlyingList();
/**
* Returns the size of the underlying list at the specified dimension or -1
* if the underlying list does not have the specified dimension.
*/
abstract int getUnderlyingSize(int... dim);
@SuppressWarnings("unchecked")
public T removeLast(int... dim) {
T toRemove;
int last = size(dim) - 1;
int[] array = add2Array(dim, last);
ListKey elementKey = new ListKey(ListKey.Type.Element, listID, array);
if (diffs.containsKey(elementKey)) {
toRemove = (T) diffs.remove(elementKey);
} else {
toRemove = uGet(array);
}
setSize(last, dim);
return toRemove;
}
int removeLastList(int... dim) {
int last = size(dim) - 1;
// Check that the list we are removing is empty.
int[] array = add2Array(dim, last);
if (0 != size(array))
throw new IllegalStateException();
ListKey sizeKeyB = new ListKey(ListKey.Type.EndPoint, listID, array);
diffs.remove(sizeKeyB);
setSize(last, dim);
return last;
}
public void set(T element, int... i) {
// Check bounds..
checkBounds(i);
int last = i[i.length - 1];
int[] dim = checkBounds(i);
ListKey elementKey = new ListKey(ListKey.Type.Element, listID, i);
boolean b = getUnderlyingSize(dim) > last;
if (b && Utils.equal(uGet(i), element)) {
if (diffs.containsKey(elementKey))
diffs.remove(elementKey);
} else {
diffs.put(elementKey, element);
}
}
private int[] checkBounds(int... i) {
int[] dim = removeFromArray(i);
int last = i[i.length - 1];
if (last >= size(dim))
throw new IndexOutOfBoundsException(String.valueOf(last));
return dim;
}
private void setSize(int size, int... dim) {
ListKey sizeKey = new ListKey(ListKey.Type.EndPoint, listID, dim);
if (getUnderlyingSize(dim) == size) {
diffs.remove(sizeKey);
} else {
diffs.put(sizeKey, new Integer(size));
}
}
public int size(int... i) {
ListKey sizeKey = new ListKey(ListKey.Type.EndPoint, listID, i);
if (diffs.containsKey(sizeKey)) {
Integer size = (Integer) diffs.get(sizeKey);
return size.intValue();
}
return getUnderlyingSize(i);
}
abstract T uGet(int... i);
// abstract int uSize(int... i);
}
Methods:
MethodJavadoc
add2Array
addDimension
addElement
checkBounds
get
getUnderlyingList
getUnderlyingSize/**
removeFromArray
removeLast
removeLastList
set
setSize/**
size
uGet
jfreerails.util.Lists
Javadoc:
/** * Utility class providing methods to compare lists of different dimensions for equality. * <p> * This class contains static methods to check if two lists (1D, 2D, or 3D) are equal by * recursively comparing their elements using the Utils.equal method. * </p> * @see List1D * @see List2D * @see List3, List3D * @see Utils */
Source code:
public class Lists {
@SuppressWarnings("unchecked")
public static boolean equals(List1D a, List1D b) {
if (a.size() != b.size())
return false;
for (int i = 0; i < a.size(); i++) {
if (!Utils.equal(a.get(i), b.get(i)))
return false;
}
return true;
}
@SuppressWarnings("unchecked")
public static boolean equals(List2D a, List2D b) {
if (a.sizeD1() != b.sizeD1())
return false;
for (int d1 = 0; d1 < a.sizeD1(); d1++) {
if (a.sizeD2(d1) != b.sizeD2(d1))
return false;
for (int d2 = 0; d2 < a.sizeD2(d1); d2++) {
if (!Utils.equal(a.get(d1, d2), b.get(d1, d2)))
return false;
}
}
return true;
}
@SuppressWarnings("unchecked")
public static boolean equals(List3D a, List3D b) {
if (a.sizeD1() != b.sizeD1())
return false;
for (int d1 = 0; d1 < a.sizeD1(); d1++) {
if (a.sizeD2(d1) != b.sizeD2(d1))
return false;
for (int d2 = 0; d2 < a.sizeD2(d1); d2++) {
if (a.sizeD3(d1, d2) != b.sizeD3(d1, d2))
return false;
for (int d3 = 0; d3 < a.sizeD3(d1, d2); d3++) {
if (!Utils.equal(a.get(d1, d2, d3), b.get(d1, d2, d3)))
return false;
}
}
}
return true;
}
}
No methods in this class.
jfreerails.util.Pair
Javadoc:
/** * A generic class representing a pair of two elements of types A and B. * This class provides methods to access the elements, check equality, and generate a string representation. * * @see java.util.Objects for equality checks */
Source code:
public class Pair<A, B> {
private A e1;
private B e2;
public Pair(A e1, B e2) {
this.e1 = e1;
this.e2 = e2;
}
public boolean equals(Pair<A, B> other) {
if (this == other)
return true;
if (null == other)
return false;
return (e1.equals(other.e1) && e2.equals(other.e2));
}
public String toString() {
return "(" + e1.toString() + ", " + e2.toString() + ")";
}
public A getA() {
return e1;
}
public B getB() {
return e2;
}
}
Methods:
MethodJavadoc
getA
getB
jfreerails.util.Utils
Javadoc:
/** * A bunch of static methods. * * @author Luke * */
Source code:
/**
* A bunch of static methods.
*
* @author Luke
*
*/
strictfp public class Utils {
public static boolean equalsBySerialization(Serializable a, Serializable b) {
byte[] bytesA = write2ByteArray(a);
byte[] bytesB = write2ByteArray(b);
if (bytesA.length != bytesB.length)
return false;
for (int i = 0; i < bytesA.length; i++) {
if (bytesA[i] != bytesB[i])
return false;
}
return true;
}
/** Used when debugging. */
public static void write(Serializable m, String fileName) {
try {
File f = new File(fileName);
OutputStream out = new FileOutputStream(f);
ObjectOutputStream objectOut = new ObjectOutputStream(out);
objectOut.writeObject(m);
objectOut.flush();
objectOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Serializable cloneBySerialisation(Serializable m) {
try {
byte[] bytes = write2ByteArray(m);
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ObjectInputStream objectIn = new ObjectInputStream(in);
Serializable o;
o = (Serializable) objectIn.readObject();
return o;
} catch (ClassNotFoundException e) {
// Should never happen.
throw new IllegalStateException();
} catch (IOException e) {
// Should never happen.
e.printStackTrace();
throw new IllegalStateException();
}
}
private static byte[] write2ByteArray(Serializable m) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ObjectOutputStream objectOut = new ObjectOutputStream(out);
objectOut.writeObject(m);
objectOut.flush();
} catch (IOException e) {
// Should never happen.
e.printStackTrace();
throw new IllegalStateException();
}
byte[] bytes = out.toByteArray();
return bytes;
}
public static String capitalizeEveryWord(String str) {
StringBuffer result = new StringBuffer();
StringTokenizer tok = new StringTokenizer(str);
while (tok.hasMoreTokens()) {
String token = tok.nextToken().toLowerCase();
result.append(Character.toUpperCase(token.charAt(0))
+ token.substring(1) + " ");
}
return result.toString().trim();
}
public static String findConstantFieldName(Object o) {
Field[] fields = o.getClass().getFields();
for (int i = 0; i < fields.length; i++) {
int modifiers = fields[i].getModifiers();
try {
if (Modifier.isStatic(modifiers)
&& Modifier.isPublic(modifiers)) {
Object o2 = fields[i].get(null);
if (o2.equals(o)) {
return fields[i].getName();
}
}
} catch (IllegalAccessException e) {
throw new IllegalStateException();
}
}
return null;
}
/**
* Returns the largest solution of the quadratic equation ax<sup><font
* size="-1">2</font></sup> + bx + c = 0.
*
* @throws IllegalArgumentException
* if <code>a == 0</code>
* @throws IllegalArgumentException
* if <code>(b * b - 4 * a * c) < 0</code>
*/
public static double solveQuadratic(double a, double b, double c)
throws IllegalArgumentException {
if (a == 0) {
throw new IllegalArgumentException("a == 0");
}
double disc = b * b - 4 * a * c;
if (disc < 0)
throw new IllegalArgumentException("(b * b - 4 * a * c) < 0");
return (-b + StrictMath.sqrt(disc)) / (2 * a);
}
public static int hypotenuse(int a, int b) {
double d = Math.hypot(a, b);
return (int) Math.round(d);
}
/**
* Returns true if the objects are equal or both null, otherwise returns
* false. Does not throw null pointer exceptions when either of the objects
* is null.
*/
public static boolean equal(Object a, Object b) {
if (null == a || null == b) {
return null == a && null == b;
}
return a.equals(b);
}
}
Methods:
MethodJavadoc
capitalizeEveryWord
cloneBySerialisation
equal/**
equalsBySerialization
findConstantFieldName
hypotenuse
solveQuadratic/**
write/** Used when debugging. */
write2ByteArray
jfreerails.world.Constants
Javadoc:
/** * game constants * * @author Roland Spatzenegger * @version $Revision 1.1$ */
Source code:
/**
* game constants
*
* @author Roland Spatzenegger
* @version $Revision 1.1$
*/
public final class Constants {
/**
* size of a tile (height and width)
*/
public static final int TILE_SIZE = 30;
}
No methods in this class.
jfreerails.world.JavaDocPlaceholder
Javadoc:
/** * This class does nothing and is only here so that javadoc gets generated * correctly. * * @author Luke * */
Source code:
/**
* This class does nothing and is only here so that javadoc gets generated
* correctly.
*
* @author Luke
*
*/
public class JavaDocPlaceholder {
}
No methods in this class.
jfreerails.world.accounts.AddItemTransaction
Javadoc:
/** * This Transaction represents the charge/credit for buying/selling an item. * * @author Luke Lindsay * */
Source code:
/**
* This Transaction represents the charge/credit for buying/selling an item.
*
* @author Luke Lindsay
*
*/
public class AddItemTransaction implements Transaction {
private static final long serialVersionUID = 3690471411852326457L;
private final Money amount;
/** For example track. */
private final Category category;
/** For example, 4 tiles. */
private final int quantity;
/** For example, standard track. */
private final int type;
public AddItemTransaction(Category category, int type, int quantity,
Money amount) {
this.category = category;
this.type = type;
this.quantity = quantity;
this.amount = amount;
}
public Money deltaAssets() {
return amount.changeSign();
}
public Money deltaCash() {
return amount;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AddItemTransaction) {
AddItemTransaction test = (AddItemTransaction) obj;
return this.amount.equals(test.amount) && category == test.category
&& type == test.type && quantity == test.quantity;
}
return false;
}
public Category getCategory() {
return category;
}
public int getQuantity() {
return quantity;
}
public int getType() {
return type;
}
@Override
public int hashCode() {
int result;
result = category.hashCode();
result = 29 * result + type;
result = 29 * result + quantity;
result = 29 * result + amount.hashCode();
return result;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("AddItemTransaction ");
sb.append(category);
sb.append(", type ");
sb.append(type);
sb.append(", quantity ");
sb.append(quantity);
sb.append(", amount ");
sb.append(amount);
return sb.toString();
}
}
Methods:
MethodJavadoc
deltaAssets
deltaCash
getCategory
getQuantity
getType
jfreerails.world.accounts.Bill
Javadoc:
/** * For example, the cost of buying a trains. * * @author Luke Lindsay * */
Source code:
/**
* For example, the cost of buying a trains.
*
* @author Luke Lindsay
*
*/
public class Bill implements Transaction {
private static final long serialVersionUID = 3258416144497782835L;
private final Money amount;
private final Category category;
public Bill(Money amount, Category category) {
this.amount = new Money(-amount.getAmount());
this.category = category;
}
public Money deltaAssets() {
return amount.changeSign();
}
public Money deltaCash() {
return amount;
}
@Override
public boolean equals(Object o) {
if (o instanceof Bill) {
Bill test = (Bill) o;
return test.amount.equals(amount) && category == test.category;
}
return false;
}
public Category getCategory() {
return category;
}
@Override
public int hashCode() {
int result;
result = amount.hashCode();
result = 29 * result + category.hashCode();
return result;
}
}
Methods:
MethodJavadoc
deltaAssets
deltaCash/**
getCategory
jfreerails.world.accounts.BondTransaction
Javadoc:
/** * A Transaction that adds or removes a Bond. * * @author Luke * */
Source code:
/**
* A Transaction that adds or removes a Bond.
*
* @author Luke
*
*/
public class BondTransaction extends AddItemTransaction {
private static final long serialVersionUID = 3257562923491473465L;
public static final Money BOND_VALUE_ISSUE = new Money(500000);
public static final Money BOND_VALUE_REPAY = new Money(-500000);
private BondTransaction(Category category, int type, int quantity,
Money amount) {
super(category, type, quantity, amount);
}
public static BondTransaction issueBond(int interestRate) {
return new BondTransaction(Category.BOND, interestRate, 1,
BOND_VALUE_ISSUE);
}
public static BondTransaction repayBond(int interestRate) {
return new BondTransaction(Category.BOND, interestRate, -1,
BOND_VALUE_REPAY);
}
}
Methods:
MethodJavadoc
issueBond
repayBond
jfreerails.world.accounts.DeliverCargoReceipt
Javadoc:
/** * A credit for delivering cargo. * * @author Luke * */
Source code:
/**
* A credit for delivering cargo.
*
* @author Luke
*
*/
public class DeliverCargoReceipt extends Receipt {
private static final long serialVersionUID = 3257009851963160372L;
private final CargoBatch cb;
private final int quantity;
private final int stationId;
private final int trainId;
public DeliverCargoReceipt(Money m, int quantity, int stationId,
CargoBatch cb, int trainId) {
super(m, Category.CARGO_DELIVERY);
this.stationId = stationId;
this.quantity = quantity;
this.cb = cb;
this.trainId = trainId;
}
public int getTrainId() {
return trainId;
}
public CargoBatch getCb() {
return cb;
}
public int getQuantity() {
return quantity;
}
public int getStationId() {
return stationId;
}
}
Methods:
MethodJavadoc
getCb
getQuantity
getStationId
getTrainId/**
jfreerails.world.accounts.EconomicClimate
Javadoc:
/** * Represents the state of the economy. * * @author Luke * */
Source code:
/**
* Represents the state of the economy.
*
* @author Luke
*
*/
public class EconomicClimate implements FreerailsSerializable {
private static final long serialVersionUID = 3834025840475321136L;
private static int i = 2;
private final String name;
public static final EconomicClimate BOOM = new EconomicClimate(i++, "BOOM");
public static final EconomicClimate PROSPERITY = new EconomicClimate(i++,
"PROSPERITY");
public static final EconomicClimate MODERATION = new EconomicClimate(i++,
"MODERATION");
public static final EconomicClimate RECESSION = new EconomicClimate(i++,
"RECESSION");
public static final EconomicClimate PANIC = new EconomicClimate(i++,
"PANIC");
public int getBaseInterestRate() {
return baseInterestRate;
}
private final int baseInterestRate;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof EconomicClimate)) {
return false;
}
final EconomicClimate economicClimate = (EconomicClimate) o;
if (baseInterestRate != economicClimate.baseInterestRate) {
return false;
}
if (name != null ? !name.equals(economicClimate.name)
: economicClimate.name != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result;
result = (name != null ? name.hashCode() : 0);
result = 29 * result + baseInterestRate;
return result;
}
private EconomicClimate(int r, String s) {
baseInterestRate = r;
name = s;
}
}
Methods:
MethodJavadoc
getBaseInterestRate
jfreerails.world.accounts.Receipt
Javadoc:
/** * A credit. * * @author Luke Lindsay * */
Source code:
/**
* A credit.
*
* @author Luke Lindsay
*
*/
public class Receipt implements Transaction {
private static final long serialVersionUID = 3617576007066924596L;
private final Money amount;
private final Category category;
public Receipt(Money m, Category category) {
this.amount = m;
this.category = category;
}
public Money deltaAssets() {
return amount.changeSign();
}
public Money deltaCash() {
return amount;
}
@Override
public boolean equals(Object o) {
if (o instanceof Receipt) {
Receipt test = (Receipt) o;
return test.amount.equals(amount) && category == test.category;
}
return false;
}
public Category getCategory() {
return category;
}
@Override
public int hashCode() {
int result;
result = amount.hashCode();
result = 29 * result + category.hashCode();
return result;
}
}
Methods:
MethodJavadoc
deltaAssets
deltaCash
getCategory
jfreerails.world.accounts.StockTransaction
Javadoc:
/** * A transaction that occurs when a new company is founded or when a company * issues additional shares. * * @author Luke * @author smackay */
Source code:
/**
* A transaction that occurs when a new company is founded or when a company
* issues additional shares.
*
* @author Luke
* @author smackay
*/
public class StockTransaction extends AddItemTransaction {
private static final long serialVersionUID = 3256441412924224824L;
public static final int STOCK_BUNDLE_SIZE = 10000;
private StockTransaction(Category category, int playerId, int quantity,
Money amount) {
super(category, playerId, quantity, amount);
if (playerId < 0)
throw new IllegalArgumentException();
}
public static StockTransaction issueStock(int playerId, int quantity,
Money pricePerShare) {
// Issue Stock of the Player
long temp = (pricePerShare.getAmount() * quantity);
temp = temp - temp - temp;
Money amount = new Money(temp).changeSign();
return new StockTransaction(Transaction.Category.ISSUE_STOCK, playerId,
quantity, amount);
}
public static StockTransaction buyOrSellStock(int playerId, int quantity,
Money stockPrice) {
// Buys another Players Stock, Uses another Category
Money value = new Money(stockPrice.getAmount() * quantity * -1);
return new StockTransaction(Transaction.Category.TRANSFER_STOCK,
playerId, quantity, value);
}
public static StockTransaction issueStock(int quantity, long pricePerShare) {
Money amount = new Money(pricePerShare * quantity);
return new StockTransaction(quantity, amount);
}
private StockTransaction(int quantity, Money amount) {
super(Transaction.Category.ISSUE_STOCK, -1, quantity, amount);
}
}
Methods:
MethodJavadoc
buyOrSellStock
issueStock
issueStock
jfreerails.world.accounts.Transaction
Javadoc:
/** * A Transaction is a change in a player's bank balance and/or assets. * * @author Luke Lindsay * */
Source code:
/**
* A Transaction is a change in a player's bank balance and/or assets.
*
* @author Luke Lindsay
*
*/
public interface Transaction extends FreerailsSerializable {
public enum Category {
BOND, BRIDGES, CARGO_DELIVERY, INDUSTRIES, INTEREST_CHARGE, ISSUE_STOCK, MISC_INCOME, STATION_MAINTENANCE, STATIONS, TRACK, TRACK_MAINTENANCE, TRAIN, TRAIN_MAINTENANCE, TRANSFER_STOCK
}
Money deltaAssets();
/** Positive means credit. */
Money deltaCash();
Category getCategory();
}
Methods:
MethodJavadoc
deltaAssets
deltaCash/** Positive means credit. */
getCategory
jfreerails.world.accounts.TransactionAndTimeStamp
Javadoc:
/** * Represents a pair of a transaction and a timestamp, used to track when a transaction occurred in a game context. * This class encapsulates a {@link Transaction} object and a {@link GameTime} object, providing immutable access to both. * It implements {@link FreerailsSerializable} to support serialization for saving game states or transmitting data. * * @see Transaction * @see GameTime * @see FreerailsSerializable */
Source code:
public class TransactionAndTimeStamp implements FreerailsSerializable {
private static final long serialVersionUID = 1540065347606694456L;
private final Transaction t;
private final GameTime timeStamp;
public TransactionAndTimeStamp(Transaction t, GameTime stamp) {
this.t = t;
timeStamp = stamp;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TransactionAndTimeStamp))
return false;
final TransactionAndTimeStamp transactionAndTimeStamp = (TransactionAndTimeStamp) o;
if (!t.equals(transactionAndTimeStamp.t))
return false;
if (!timeStamp.equals(transactionAndTimeStamp.timeStamp))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = t.hashCode();
result = 29 * result + timeStamp.hashCode();
return result;
}
public Transaction getT() {
return t;
}
public GameTime getTimeStamp() {
return timeStamp;
}
}
Methods:
MethodJavadoc
getT
getTimeStamp
jfreerails.world.cargo.CargoBatch
Javadoc:
/** * This class represents a cargo batch (cargo of the same batch is cargo of the * same type that was produced at the same location at the same time). * * @author Luke */
Source code:
/**
* This class represents a cargo batch (cargo of the same batch is cargo of the
* same type that was produced at the same location at the same time).
*
* @author Luke
*/
public class CargoBatch implements FreerailsSerializable,
Comparable<CargoBatch> {
private static final long serialVersionUID = 3257006557605540149L;
private final int cargoType;
private final int sourceX;
private final int sourceY;
private final int stationOfOrigin;
private final long timeCreated;
public CargoBatch(int type, int x, int y, long time, int origin) {
cargoType = type;
sourceX = x;
sourceY = y;
timeCreated = time;
stationOfOrigin = origin;
}
public int getStationOfOrigin() {
return stationOfOrigin;
}
public int getCargoType() {
return cargoType;
}
public int getSourceX() {
return sourceX;
}
public int getSourceY() {
return sourceY;
}
public long getTimeCreated() {
return timeCreated;
}
@Override
public boolean equals(Object o) {
if (o instanceof CargoBatch) {
CargoBatch test = (CargoBatch) o;
if (test.getCargoType() == this.cargoType
&& test.getSourceX() == this.sourceX
&& test.sourceY == this.sourceY
&& test.timeCreated == this.timeCreated
&& test.stationOfOrigin == this.stationOfOrigin) {
return true;
}
return false;
}
return false;
}
@Override
public int hashCode() {
int result = 17;
result = 37 * result + this.cargoType;
result = 37 * result + this.sourceX;
result = 37 * result + this.sourceY;
result = 37 * result + this.stationOfOrigin;
result = 37 * result
+ (int) (this.timeCreated ^ (this.timeCreated >>> 32));
return result;
}
public int compareTo(CargoBatch o) {
if (timeCreated != o.timeCreated)
return (int) (timeCreated - o.timeCreated);
if (cargoType != o.cargoType)
return (cargoType - o.cargoType);
if (stationOfOrigin != o.stationOfOrigin)
return (stationOfOrigin - o.stationOfOrigin);
if (sourceX != o.sourceX)
return (sourceX - o.sourceX);
if (sourceY != o.sourceY)
return (sourceY - o.sourceY);
return 0;
}
}
Methods:
MethodJavadoc
compareTo
getCargoType
getSourceX
getSourceY
getStationOfOrigin
getTimeCreated
jfreerails.world.cargo.CargoBundle
Javadoc:
/** * Represents a collection of CargoBatch objects, providing methods to iterate over batches, * check for their presence, retrieve amounts by batch or cargo type, and determine the size. * The iterator is fail-fast and throws ConcurrentModificationException if the bundle is modified * while iterating. * * @see CargoBatch */
Source code:
public interface CargoBundle {
/**
* Note, calling hasNext() or next() on the returned iterator throws a
* ConcurrentModificationException if this CargoBundle has changed since the
* iterator was acquired.
*/
Iterator<CargoBatch> cargoBatchIterator();
boolean contains(CargoBatch cb);
int getAmount(CargoBatch cb);
int getAmount(int cargoType);
int size();
}
Methods:
MethodJavadoc
cargoBatchIterator/**
contains
getAmount
getAmount
size
jfreerails.world.cargo.CargoType
Javadoc:
/** * Represents a type of cargo. * * @author luke */
Source code:
/**
* Represents a type of cargo.
*
* @author luke
*/
final public class CargoType implements FreerailsSerializable {
private static final long serialVersionUID = 3834874680581369912L;
public enum Categories {
Mail(0), Passengers(1), Fast_Freight(2), Slow_Freight(3), Bulk_Freight(
4);
private int nr;
private Categories(int nr) {
this.nr = nr;
}
public int getNumber() {
return nr;
}
public static Categories getCategory(String cat) {
for (Categories cmp : values()) {
if (cmp.toString().equals(cat)) {
return cmp;
}
}
throw new IllegalArgumentException("Category:" + cat + " unknown.");
}
};
public static int getNumberOfCategories() {
return Categories.values().length;
}
private final Categories category;
private final String name;
private final int unitWeight;
public CargoType(int weight, String s, Categories cat) {
unitWeight = weight;
category = cat;
name = s;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof CargoType))
return false;
CargoType other = (CargoType) obj;
return other.unitWeight == this.unitWeight && other.name.equals(name)
&& other.category.equals(category);
}
public Categories getCategory() {
return category;
}
/** Returns the name, replacing any underscores with spaces. */
public String getDisplayName() {
return this.name.replace('_', ' ');
}
public String getName() {
return name;
}
public int getUnitWeight() {
return unitWeight;
}
@Override
public int hashCode() {
int result;
result = unitWeight;
result = 29 * result + category.hashCode();
result = 29 * result + name.hashCode();
return result;
}
@Override
public String toString() {
return name;
}
}
Methods:
MethodJavadoc
getCategory
getDisplayName/** Returns the name, replacing any underscores with spaces. */
getName
getNumberOfCategories
getUnitWeight
jfreerails.world.cargo.ImmutableCargoBundle
Javadoc:
/** * This class represents a bundle of cargo made up of quantities of cargo from * different {@link CargoBatch}s. * <p> * For example: * </p> * <table border="" summary="example"> * <tr> * <td><strong>Cargo Batch</strong></td> * <td><strong>Quantity</strong></td> * </tr> * <tr> * <td>passengers from (1, 5) created at 01:00</td> * <td>2</td> * </tr> * <tr> * <td>passengers from (1, 5) created at 01:25</td> * <td>1</td> * </tr> * <tr> * <td>coal from (4,10) created at 02:50</td> * <td>8</td> * </tr> * <tr> * <td>mail from (6, 10) created at 04:45</td> * <td>10</td> * </tr> * </table> * * @author Luke * */
Source code:
/**
* This class represents a bundle of cargo made up of quantities of cargo from
* different {@link CargoBatch}s.
* <p>
* For example:
* </p>
* <table border="" summary="example">
* <tr>
* <td><strong>Cargo Batch</strong></td>
* <td><strong>Quantity</strong></td>
* </tr>
* <tr>
* <td>passengers from (1, 5) created at 01:00</td>
* <td>2</td>
* </tr>
* <tr>
* <td>passengers from (1, 5) created at 01:25</td>
* <td>1</td>
* </tr>
* <tr>
* <td>coal from (4,10) created at 02:50</td>
* <td>8</td>
* </tr>
* <tr>
* <td>mail from (6, 10) created at 04:45</td>
* <td>10</td>
* </tr>
* </table>
*
* @author Luke
*
*/
public class ImmutableCargoBundle implements CargoBundle, FreerailsSerializable {
public static final ImmutableCargoBundle EMPTY_BUNDLE = new ImmutableCargoBundle();
private static final long serialVersionUID = 3257566187666814009L;
public static boolean equals(CargoBundle a, CargoBundle b) {
Iterator<CargoBatch> it = a.cargoBatchIterator();
if (a.size() != b.size())
return false;
while (it.hasNext()) {
CargoBatch batch = it.next();
if (a.getAmount(batch) != b.getAmount(batch)) {
return false;
}
}
return true;
}
private final ImInts amounts;
private final ImList<CargoBatch> batches;
private ImmutableCargoBundle() {
batches = new ImList<CargoBatch>();
amounts = new ImInts();
}
public ImmutableCargoBundle(SortedMap<CargoBatch, Integer> sortedMap) {
int size = sortedMap.size();
int[] amountsArray = new int[size];
CargoBatch[] batchesArray = new CargoBatch[size];
int i = 0;
for (CargoBatch batch : sortedMap.keySet()) {
batchesArray[i] = batch;
amountsArray[i] = sortedMap.get(batch);
i++;
}
batches = new ImList<CargoBatch>(batchesArray);
amounts = new ImInts(amountsArray);
}
public Iterator<CargoBatch> cargoBatchIterator() {
return new Iterator<CargoBatch>() {
int index = 0;
public boolean hasNext() {
return index < batches.size();
}
public CargoBatch next() {
CargoBatch o = batches.get(index);
index++;
return o;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public boolean contains(CargoBatch cb) {
for (int i = 0; i < batches.size(); i++) {
if (batches.get(i).equals(cb)) {
return true;
}
}
return false;
}
@Override
public boolean equals(Object arg0) {
if (null == arg0) {
return false;
}
if (!(arg0 instanceof CargoBundle)) {
return false;
}
return equals(this, (CargoBundle) arg0);
}
public int getAmount(CargoBatch cb) {
int amount = 0;
for (int i = 0; i < batches.size(); i++) {
if (batches.get(i).equals(cb)) {
amount += amounts.get(i);
}
}
return amount;
}
public int getAmount(int cargoType) {
int amount = 0;
for (int i = 0; i < batches.size(); i++) {
if (batches.get(i).getCargoType() == cargoType) {
amount += amounts.get(i);
}
}
return amount;
}
@Override
public int hashCode() {
return amounts.size();
}
public int size() {
return batches.size();
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("CargoBundle {\n");
for (int i = 0; i < batches.size(); i++) {
sb.append(amounts.get(i));
sb.append(" units of cargo type ");
sb.append(batches.get(i));
sb.append("\n");
}
sb.append("}");
return sb.toString();
}
}
Methods:
MethodJavadoc
cargoBatchIterator
contains
getAmount
getAmount
size
jfreerails.world.cargo.MutableCargoBundle
Javadoc:
/** * This CargoBundle implementation uses a <code>java.util.SortedMap</code> to * map quantities to cargo batches. * * @author Luke * */
Source code:
/**
* This CargoBundle implementation uses a <code>java.util.SortedMap</code> to
* map quantities to cargo batches.
*
* @author Luke
*
*/
public class MutableCargoBundle implements CargoBundle {
private final SortedMap<CargoBatch, Integer> sortedMap;
private int updateID = 0;
public MutableCargoBundle() {
sortedMap = new TreeMap<CargoBatch, Integer>();
}
public MutableCargoBundle(ImmutableCargoBundle imcb) {
this();
Iterator<CargoBatch> it = imcb.cargoBatchIterator();
while (it.hasNext()) {
CargoBatch cb = it.next();
addCargo(cb, imcb.getAmount(cb));
}
}
public void addCargo(CargoBatch cb, int amount) {
int amountAlready = this.getAmount(cb);
this.setAmount(cb, amount + amountAlready);
updateID++;
}
/**
* Note, calling hasNext() or next() on the returned iterator throws a
* ConcurrentModificationException if this CargoBundle has changed since the
* iterator was acquired.
*/
public Iterator<CargoBatch> cargoBatchIterator() {
final Iterator<CargoBatch> it = sortedMap.keySet().iterator();
/*
* A ConcurrentModificationException used to get thrown when the amount
* of cargo was set to 0, since this resulted in the key being removed
* from the hashmap. The iterator below throws a
* ConcurrentModificationException whenever this CargoBundle has been
* changed since the iterator was acquired. This should mean that if the
* cargo bundle gets changed while the iterator is in use, you will know
* about it straight away.
*/
return new Iterator<CargoBatch>() {
final int updateIDAtCreation = updateID;
public boolean hasNext() {
if (updateIDAtCreation != updateID) {
throw new ConcurrentModificationException();
}
return it.hasNext();
}
public CargoBatch next() {
if (updateIDAtCreation != updateID) {
throw new ConcurrentModificationException();
}
return it.next();
}
public void remove() {
throw new UnsupportedOperationException(
"Use CargoBundle.setAmount(CargoBatch cb, 0)");
}
};
}
public boolean contains(CargoBatch cb) {
return sortedMap.containsKey(cb);
}
@Override
public boolean equals(Object arg0) {
if (null == arg0) {
return false;
}
if (!(arg0 instanceof CargoBundle)) {
return false;
}
return ImmutableCargoBundle.equals(this, (CargoBundle) arg0);
}
public int getAmount(CargoBatch cb) {
if (contains(cb)) {
Integer i = sortedMap.get(cb);
return i.intValue();
}
return 0;
}
public int getAmount(int cargoType) {
Iterator<CargoBatch> it = cargoBatchIterator();
int amount = 0;
while (it.hasNext()) {
CargoBatch cb = it.next();
if (cb.getCargoType() == cargoType) {
amount += getAmount(cb);
}
}
return amount;
}
@Override
public int hashCode() {
return sortedMap.size();
}
public void setAmount(CargoBatch cb, int amount) {
if (0 == amount) {
sortedMap.remove(cb);
} else {
sortedMap.put(cb, new Integer(amount));
}
updateID++;
}
public int size() {
return sortedMap.size();
}
public ImmutableCargoBundle toImmutableCargoBundle() {
return new ImmutableCargoBundle(sortedMap);
}
@Override
public String toString() {
return toImmutableCargoBundle().toString();
}
}
Methods:
MethodJavadoc
addCargo
cargoBatchIterator/**
contains
getAmount
getAmount
setAmount
size
toImmutableCargoBundle
jfreerails.world.common.Activity
Javadoc:
/** * Represents an activity with a duration and state transitions over time. * This interface defines methods to retrieve the duration of the activity * and to determine its state at a given time delta. * * @see FreerailsSerializable */
Source code:
public interface Activity<E extends FreerailsSerializable> extends
FreerailsSerializable {
double duration();
E getState(double dt);
}
Methods:
MethodJavadoc
duration
getState
jfreerails.world.common.ActivityIterator
Javadoc:
/** * This interface provides a bidirectional iterator for traversing a sequence of activities, * allowing access to their time-related properties and navigation between activities. * It supports methods to retrieve start and finish times, convert absolute time to relative * time, and obtain the current activity's state and details. * * @see Activity * @see FreerailsSerializable */
Source code:
public interface ActivityIterator {
boolean hasNext();
void nextActivity() throws NoSuchElementException;
/** Returns the time the current activity starts. */
double getStartTime();
/** Returns the time the current activity ends. */
double getFinishTime();
double getDuration();
/**
* Converts an absolute time value to a time value relative to the start of
* the current activity. If absoluteTime > getFinishTime(), getDuration() is
* returned.
*/
double absolute2relativeTime(double absoluteTime);
FreerailsSerializable getState(double absoluteTime);
Activity getActivity();
void gotoLastActivity();
void previousActivity() throws NoSuchElementException;
boolean hasPrevious();
}
Methods:
MethodJavadoc
absolute2relativeTime/**
getActivity
getDuration
getFinishTime/** Returns the time the current activity ends. */
getStartTime/** Returns the time the current activity starts. */
getState
gotoLastActivity
hasNext
hasPrevious
nextActivity
previousActivity
jfreerails.world.common.FlatTrackTemplate
Javadoc:
/** * Defines methods that encode a track configuration as an int. * * @author Luke */
Source code:
/**
* Defines methods that encode a track configuration as an int.
*
* @author Luke
*/
public interface FlatTrackTemplate extends FreerailsSerializable {
/**
* @param ftt
* the FlatTrackTemplate which may be a subset of this
* FlatTrackTemplate.
* @return true if the vectors represented by this FlatTrackTemplate are a
* superset of the vectors of the specified FlatTrackTemplate
*/
boolean contains(FlatTrackTemplate ftt);
/**
* @return the integer representing the vector(s) of this object.
*/
int get9bitTemplate();
}
Methods:
MethodJavadoc
contains/**
get9bitTemplate/**
jfreerails.world.common.FreerailsMutableSerializable
Javadoc:
/** * This interface tags mutable serializable classes. * * @author Luke */
Source code:
/**
* This interface tags mutable serializable classes.
*
* @author Luke
*/
public interface FreerailsMutableSerializable extends Serializable {
}
No methods in this class.
jfreerails.world.common.FreerailsPathIterator
Javadoc:
/** * This interface lets the caller retrieve a path made up of a series of * straight lines. E.g. it lets the path a train takes across a section of track * be retrieved without revealing the underlying objects that represent the * track. * * @author luke */
Source code:
/**
* This interface lets the caller retrieve a path made up of a series of
* straight lines. E.g. it lets the path a train takes across a section of track
* be retrieved without revealing the underlying objects that represent the
* track.
*
* @author luke
*/
public interface FreerailsPathIterator extends FreerailsMutableSerializable {
/**
* Tests whether the path has another segment.
*/
boolean hasNext();
/**
* Gets the next segment of the path and places its coordinates in the
* specified IntLine; then moves the iterator forwards by one path segment.
* (The coordinates are placed the passed-in IntLine rather than a new
* object to avoid the cost of object creation.)
*
* @param line
*/
void nextSegment(IntLine line);
}
Methods:
MethodJavadoc
hasNext/**
nextSegment/**
jfreerails.world.common.FreerailsPathIteratorImpl
Javadoc:
/** * Lets the caller access a series of Points as a series of IntLines. * * @author Luke Lindsay */
Source code:
/**
* Lets the caller access a series of Points as a series of IntLines.
*
* @author Luke Lindsay
*/
public class FreerailsPathIteratorImpl implements FreerailsPathIterator {
private static final long serialVersionUID = 3258411750679720758L;
public static FreerailsPathIterator forwardsIterator(List<Point> l) {
return new FreerailsPathIteratorImpl(l, true);
}
public static FreerailsPathIterator backwardsIterator(List<Point> l) {
return new FreerailsPathIteratorImpl(l, false);
}
/** Creates new FreerailsPathIteratorImpl */
public FreerailsPathIteratorImpl(List<Point> l, boolean f) {
points = l;
forwards = f;
if (forwards) {
this.position = 0;
} else {
this.position = l.size() - 1; // The last element of a list of
// size 7 is at position 6.
}
}
private final boolean forwards;
private int position;
private final List<Point> points;
public boolean hasNext() {
if (forwards) {
return (position + 1) < points.size();
}
return (position - 1) >= 0;
}
public void nextSegment(IntLine line) {
if (hasNext()) {
Point a;
Point b;
if (forwards) {
position++;
a = points.get(position - 1);
b = points.get(position);
} else {
position--;
a = points.get(position + 1);
b = points.get(position);
}
line.x1 = a.x;
line.y1 = a.y;
line.x2 = b.x;
line.y2 = b.y;
} else {
throw new NoSuchElementException();
}
}
}
Methods:
MethodJavadoc
backwardsIterator
forwardsIterator
hasNext
nextSegment
jfreerails.world.common.FreerailsSerializable
Javadoc:
/** * This interface tags classes that can be sent between the client and the * server. * * <b> * <p> * Every class that implements this interface should be immutable. </b> * * @author Luke */
Source code:
/**
* This interface tags classes that can be sent between the client and the
* server.
*
* <b>
* <p>
* Every class that implements this interface should be immutable. </b>
*
* @author Luke
*/
public interface FreerailsSerializable extends Serializable {
}
No methods in this class.
jfreerails.world.common.GameCalendar
Javadoc:
/** * This class converts time measured in ticks since the game began into time * represented as <i>Month, Year</i> and <i>hour:minute</i>. * * @author Luke */
Source code:
/**
* This class converts time measured in ticks since the game began into time
* represented as <i>Month, Year</i> and <i>hour:minute</i>.
*
* @author Luke
*/
final public class GameCalendar implements FreerailsSerializable {
private static final long serialVersionUID = 3257568421033226805L;
private static final DecimalFormat decimalFormat = new DecimalFormat("00");
private final int ticksPerYear;
private final int startYear;
@Override
public int hashCode() {
int result;
result = ticksPerYear;
result = 29 * result + startYear;
return result;
}
public GameTime getStartOfYear(GameTime t) {
int year = getYear(t.getTicks());
int ticks = getTicks(year);
return new GameTime(ticks);
}
public String getYearAsString(int ticks) {
int i = getYear(ticks);
return String.valueOf(i);
}
public int getYear(int ticks) {
return startYear + (ticks / ticksPerYear);
}
public int getTicks(int year) {
int deltaYear = year - startYear;
return deltaYear * ticksPerYear;
}
/**
* Returns the time of day as a string, note that a year is made up of a
* representative day, so 1st June is equivalent to 12 noon.
*/
public String getTimeOfDay(int i) {
int ticksPerHour = ticksPerYear / 24;
int hour = ticksPerHour == 0 ? 0 : (i % ticksPerYear) / ticksPerHour;
int ticksPerMinute = ticksPerYear / (24 * 60);
int minute = ticksPerMinute == 0 ? 0 : (i % (ticksPerMinute * 60));
return decimalFormat.format(hour) + ":" + decimalFormat.format(minute);
}
public String getYearAndMonth(int i) {
int month = getMonth(i);
String monthAbrev = null;
switch (month) {
case 0: {
monthAbrev = "Jan";
break;
}
case 1: {
monthAbrev = "Feb";
break;
}
case 2: {
monthAbrev = "Mar";
break;
}
case 3: {
monthAbrev = "Apr";
break;
}
case 4: {
monthAbrev = "May";
break;
}
case 5: {
monthAbrev = "Jun";
break;
}
case 6: {
monthAbrev = "Jul";
break;
}
case 7: {
monthAbrev = "Aug";
break;
}
case 8: {
monthAbrev = "Sep";
break;
}
case 9: {
monthAbrev = "Oct";
break;
}
case 10: {
monthAbrev = "Nov";
break;
}
case 11: {
monthAbrev = "Dec";
break;
}
}
return monthAbrev + " " + getYearAsString(i);
}
/** Returns the month, 0=Jan, 1=Feb, etc. */
public int getMonth(int i) {
int ticksPerMonth = ticksPerYear / 12;
return (i % ticksPerYear) / ticksPerMonth;
}
public GameCalendar(int ticksPerYear, int startYear) {
this.ticksPerYear = ticksPerYear;
this.startYear = startYear;
}
@Override
public boolean equals(Object o) {
if (o instanceof GameCalendar) {
GameCalendar test = (GameCalendar) o;
if (this.startYear != test.startYear
|| this.ticksPerYear != test.ticksPerYear) {
return false;
}
return true;
}
return false;
}
public int getTicksPerYear() {
return ticksPerYear;
}
}
Methods:
MethodJavadoc
getMonth/** Returns the month, 0=Jan, 1=Feb, etc. */
getStartOfYear
getTicks
getTicksPerYear
getTimeOfDay/**
getYear
getYearAndMonth
getYearAsString
jfreerails.world.common.GameSpeed
Javadoc:
/** * This class represents actual game speed. If the game speed <code>speed</code> * is lesser then zero, game is paused. After unpausing, the speed should be * <code>-speed</code>. * * I.e. pausing/unpausing is equal to multiply the speed by -1. * * @author MystiqueAgent * */
Source code:
/**
* This class represents actual game speed. If the game speed <code>speed</code>
* is lesser then zero, game is paused. After unpausing, the speed should be
* <code>-speed</code>.
*
* I.e. pausing/unpausing is equal to multiply the speed by -1.
*
* @author MystiqueAgent
*
*/
public class GameSpeed implements FreerailsSerializable {
private static final long serialVersionUID = 3257562901983081783L;
private final int speed;
@Override
public String toString() {
return "GameSpeed:" + String.valueOf(speed);
}
public GameSpeed(int speed) {
this.speed = speed;
}
public int getSpeed() {
return speed;
}
public boolean isPaused(){
return speed < 1;
}
@Override
public boolean equals(Object o) {
if (o instanceof GameSpeed) {
GameSpeed test = (GameSpeed) o;
return this.speed == test.speed;
}
return false;
}
@Override
public int hashCode() {
return speed;
}
}
Methods:
MethodJavadoc
getSpeed
isPaused
jfreerails.world.common.GameTime
Javadoc:
/** * This class represents a specific instant in time during a game. * * @author Luke * */
Source code:
/**
* This class represents a specific instant in time during a game.
*
* @author Luke
*
*/
public class GameTime implements FreerailsSerializable, Comparable<GameTime> {
private static final long serialVersionUID = 3691035461301055541L;
/** The first possible time. */
public static final GameTime BIG_BANG = new GameTime(Integer.MIN_VALUE);
/** The last possible time. */
public static final GameTime END_OF_THE_WORLD = new GameTime(
Integer.MAX_VALUE);
private final int ticks;
@Override
public String toString() {
return "GameTime:" + String.valueOf(ticks);
}
@Override
public int hashCode() {
return ticks;
}
public GameTime(int l) {
this.ticks = l;
}
public GameTime nextTick() {
return new GameTime(ticks + 1);
}
public int getTicks() {
return ticks;
}
@Override
public boolean equals(Object o) {
if (o instanceof GameTime) {
GameTime test = (GameTime) o;
return this.ticks == test.ticks;
}
return false;
}
/**
* Compares two GameTimes for ordering.
*
* @param t
* @return 0 if t is equal to this GameTime; a value less than 0 if this
* GameTime is before t; and a value greater than 0 if this GameTime
* is after t.
*/
public int compareTo(GameTime t) {
return ticks - t.ticks;
}
}
Methods:
MethodJavadoc
compareTo/**
getTicks
nextTick
jfreerails.world.common.ImHashSet
Javadoc:
/** * <p> * ImHashSet is an immutable wrapper class for a {@link HashSet} that ensures * the contents cannot be modified after creation. It provides immutability * guarantees and implements the {@link FreerailsSerializable} interface for * serialization support. * </p> * <p> * This class delegates all operations to an internal {@link HashSet} instance * but enforces immutability by making all modifications (such as adding or * removing elements) unsupported. The iterator returned by {@link #iterator()} * does not allow removal of elements. * </p> * * @since 1.0 * @see HashSet * @see FreerailsSerializable * @see java.util.Iterator * @see java.util.Set */
Source code:
@Immutable
public class ImHashSet<E extends FreerailsSerializable> implements
FreerailsSerializable {
private static final long serialVersionUID = -4098862905501171517L;
private final HashSet<E> hashSet;
public ImHashSet(HashSet<E> hashSet) {
this.hashSet = new HashSet<E>(hashSet);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImHashSet))
return false;
final ImHashSet imHashSet = (ImHashSet) o;
if (!hashSet.equals(imHashSet.hashSet))
return false;
return true;
}
@Override
public int hashCode() {
return hashSet.hashCode();
}
public ImHashSet(E... values) {
this.hashSet = new HashSet<E>();
for (E e : values) {
hashSet.add(e);
}
}
public ImHashSet(List<E> values) {
this.hashSet = new HashSet<E>();
for (E e : values) {
hashSet.add(e);
}
}
public boolean contains(E e) {
return hashSet.contains(e);
}
public Iterator<E> iterator() {
return new Iterator<E>() {
Iterator<E> it = hashSet.iterator();
public boolean hasNext() {
return it.hasNext();
}
public E next() {
return it.next();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
Methods:
MethodJavadoc
contains
iterator
jfreerails.world.common.ImInts
Javadoc:
/** * An immutable list of ints. * * @author Luke * */
Source code:
/**
* An immutable list of ints.
*
* @author Luke
*
*/
@Immutable
public class ImInts implements FreerailsSerializable {
private static final long serialVersionUID = -7171552118713000676L;
private final int ints[];
public ImInts(int... i) {
this.ints = i.clone();
}
public static ImInts fromBoolean(boolean... i) {
int[] ii = new int[i.length];
for (int j = 0; j < i.length; j++) {
ii[j] = i[j] ? 1 : 0;
}
return new ImInts(ii);
}
public int size() {
return ints.length;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImInts))
return false;
final ImInts other = (ImInts) o;
if (!Arrays.equals(ints, other.ints))
return false;
return true;
}
@Override
public int hashCode() {
return ints.length;
}
public int get(int i) {
return ints[i];
}
public ImInts removeLast() {
int[] newInts = new int[ints.length - 1];
System.arraycopy(ints, 0, newInts, 0, newInts.length);
return new ImInts(newInts);
}
public ImInts append(int... extra) {
int[] newInts = new int[ints.length + extra.length];
System.arraycopy(ints, 0, newInts, 0, ints.length);
System.arraycopy(extra, 0, newInts, ints.length, extra.length);
return new ImInts(newInts);
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer(getClass().getName());
sb.append("[");
for (int i = 0; i < ints.length; i++) {
sb.append(ints[i]);
if (i + 1 < ints.length)
sb.append(", ");
}
sb.append("]");
return sb.toString();
}
/** Returns the sum of the ints stored in the list.*/
public int sum(){
int sum = 0;
for (int i = 0; i < ints.length; i++) {
sum+=ints[i];
}
return sum;
}
}
Methods:
MethodJavadoc
append
fromBoolean
get
removeLast
size
sum/** Returns the sum of the ints stored in the list.*/
jfreerails.world.common.ImList
Javadoc:
/** * An immutable List * * @author Luke * */
Source code:
/**
* An immutable List
*
* @author Luke
*
*/
@Immutable
public final class ImList<E extends FreerailsSerializable> implements
FreerailsSerializable {
private static final long serialVersionUID = 2669191159273299313L;
private final E[] elementData;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImList))
return false;
final ImList imList = (ImList) o;
if (!Arrays.equals(elementData, imList.elementData))
return false;
return true;
}
@Override
public int hashCode() {
return elementData.length;
}
@SuppressWarnings("unchecked")
public ImList(E... items) {
elementData = (E[]) new FreerailsSerializable[items.length];
for (int i = 0; i < items.length; i++) {
elementData[i] = items[i];
}
}
@SuppressWarnings("unchecked")
public ImList(List<E> list) {
elementData = (E[]) new FreerailsSerializable[list.size()];
for (int i = 0; i < list.size(); i++) {
elementData[i] = list.get(i);
}
}
public void checkForNulls() throws NullPointerException {
for (int i = 0; i < elementData.length; i++) {
if (null == elementData[i])
throw new NullPointerException();
}
}
public int size() {
return elementData.length;
}
public E get(int i) {
return elementData[i];
}
}
Methods:
MethodJavadoc
checkForNulls/**
get
size
jfreerails.world.common.ImPoint
Javadoc:
/** * An immutable point. * * @author Luke * */
Source code:
/**
* An immutable point.
*
* @author Luke
*
*/
@Immutable
public final class ImPoint implements FreerailsSerializable, Comparable<ImPoint> {
private static final long serialVersionUID = -3053020239886388576L;
public final int x, y;
public ImPoint() {
x = 0;
y = 0;
}
public ImPoint(Point p) {
x = p.x;
y = p.y;
}
public ImPoint(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImPoint))
return false;
final ImPoint imPoint = (ImPoint) o;
if (x != imPoint.x)
return false;
if (y != imPoint.y)
return false;
return true;
}
public Point toPoint() {
return new Point(x, y);
}
@Override
public int hashCode() {
return x * 1000 + y;
}
@Override
public String toString() {
return "ImPoint{" + x + ", " + y + "}";
}
public int compareTo(ImPoint o) {
if (o.y != y)
return y - o.y;
else
return x - o.x;
}
}
Methods:
MethodJavadoc
compareTo
toPoint/**
jfreerails.world.common.ImSet
Javadoc:
/** * An immutable set. * * @author Luke * */
Source code:
/**
* An immutable set.
*
* @author Luke
*
*/
@Immutable
public final class ImSet<E extends FreerailsSerializable> implements
FreerailsSerializable {
private static final long serialVersionUID = -8075637749158447780L;
private final HashSet<E> hashSet;
public ImSet(Set<E> data) {
hashSet = new HashSet<E>(data);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImSet))
return false;
final ImSet imSet = (ImSet) o;
if (!hashSet.equals(imSet.hashSet))
return false;
return true;
}
@Override
public int hashCode() {
return hashSet.hashCode();
}
public boolean contains(E element) {
return hashSet.contains(element);
}
}
Methods:
MethodJavadoc
contains
jfreerails.world.common.ImStringList
Javadoc:
/** * An immutable list of Strings. * * @author Luke * */
Source code:
/**
* An immutable list of Strings.
*
* @author Luke
*
*/
@Immutable
public class ImStringList implements FreerailsSerializable {
private static final long serialVersionUID = 5211786598838212188L;
private final String[] strings;
public ImStringList(String... strings) {
this.strings = strings.clone();
}
public String get(int i) {
return strings[i];
}
public int size() {
return strings.length;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImStringList))
return false;
final ImStringList imStringList = (ImStringList) o;
if (!Arrays.equals(strings, imStringList.strings))
return false;
return true;
}
@Override
public int hashCode() {
return strings.length;
}
}
Methods:
MethodJavadoc
get
size
jfreerails.world.common.IntLine
Javadoc:
/** * This class defines a straight line between two points. Units are arbitrary. * * @author Luke */
Source code:
/**
* This class defines a straight line between two points. Units are arbitrary.
*
* @author Luke
*/
public class IntLine implements Serializable {
private static final long serialVersionUID = 3257853198755705393L;
private final static int MAX_SQUAREROOTS = 64 * 256;
private final static double squareRoots[];
static {
squareRoots = new double[MAX_SQUAREROOTS];
for (int i = 0; i < MAX_SQUAREROOTS; i++) {
squareRoots[i] = Math.sqrt(i);
}
}
public int x1;
public int x2;
public int y1;
public int y2;
@Override
public int hashCode() {
int result;
result = x1;
result = 29 * result + x2;
result = 29 * result + y1;
result = 29 * result + y2;
return result;
}
/**
* @return the length of the line
*/
public double getLength() {
int sumOfSquares = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
if(sumOfSquares < MAX_SQUAREROOTS) {
return squareRoots[sumOfSquares];
}
return Math.sqrt(sumOfSquares);
}
/**
* @param xx1
* x of the first point
* @param yy1
* y of the first point
* @param xx2
* x of the second point
* @param yy2
* y of the second point
*/
public IntLine(int xx1, int yy1, int xx2, int yy2) {
x1 = xx1;
y1 = yy1;
x2 = xx2;
y2 = yy2;
}
/**
* Default constructor - defines a dot at 0,0.
*/
public IntLine() {
}
@Override
public boolean equals(Object o) {
if (null == o) {
return false;
}
if (o == this) {
return true;
}
if (o instanceof IntLine) {
IntLine line = (IntLine) o;
if (line.x1 == this.x1 && line.x2 == this.x2 && line.y1 == this.y1
&& line.y2 == this.y2) {
return true;
}
return false;
}
return false;
}
@Override
public String toString() {
return "(" + x1 + ", " + y1 + ", " + x2 + ", " + y2 + ")";
}
}
Methods:
MethodJavadoc
getLength/**
jfreerails.world.common.Money
Javadoc:
/** * Represents an amount of Money. * * @author Luke */
Source code:
/**
* Represents an amount of Money.
*
* @author Luke
*/
final public class Money implements FreerailsSerializable {
private static final long serialVersionUID = 3258697615163338805L;
public static final Money ZERO = new Money(0);
private static final DecimalFormat df = new DecimalFormat("#,###");
private final long amount;
public long getAmount() {
return amount;
}
@Override
public int hashCode() {
return (int) (amount ^ (amount >>> 32));
}
@Override
public String toString() {
return df.format(amount);
}
public Money(long amount) {
this.amount = amount;
}
public Money changeSign() {
return new Money(-amount);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Money) {
Money test = (Money) obj;
return test.amount == this.amount;
}
return false;
}
}
Methods:
MethodJavadoc
changeSign
getAmount
jfreerails.world.common.PositionOnTrack
Javadoc:
/** * A <b>mutable</b> class that stores the coordinates of the tile on entity is * standing on and the direction in which the entity is facing (usually the * direction the entity as just been moving - the opposite to the direction it * came from), it provides methods to encode and decode its field values to and * from a single int. * * @author Luke */
Source code:
/**
* A <b>mutable</b> class that stores the coordinates of the tile on entity is
* standing on and the direction in which the entity is facing (usually the
* direction the entity as just been moving - the opposite to the direction it
* came from), it provides methods to encode and decode its field values to and
* from a single int.
*
* @author Luke
*/
public final class PositionOnTrack implements FreerailsMutableSerializable {
private static final int BITS_FOR_COORDINATE = 14;
private static final int BITS_FOR_DIRECTION = 3;
public static final int MAX_COORDINATE = (1 << BITS_FOR_COORDINATE) - 1;
public static final int MAX_DIRECTION = (1 << BITS_FOR_DIRECTION) - 1;
private static final long serialVersionUID = 3257853198755707184L;
public static PositionOnTrack createComingFrom(int x, int y, Step direction) {
return new PositionOnTrack(x, y, direction);
}
public static PositionOnTrack createFacing(int x, int y, Step direction) {
return new PositionOnTrack(x, y, direction.getOpposite());
}
public static PositionOnTrack[] fromInts(int[] ints) {
PositionOnTrack[] returnValue = new PositionOnTrack[ints.length];
for (int i = 0; i < ints.length; i++) {
PositionOnTrack p = new PositionOnTrack(ints[i]);
returnValue[i] = p;
}
return returnValue;
}
public static int[] toInts(PositionOnTrack[] pos) {
int[] returnValue = new int[pos.length];
for (int i = 0; i < pos.length; i++) {
returnValue[i] = pos[i].toInt();
}
return returnValue;
}
/** The direction from which we entered the tile. */
private Step cameFrom = Step.NORTH;
private int x = 0;
private int y = 0;
public PositionOnTrack() {
}
public PositionOnTrack(int i) {
this.setValuesFromInt(i);
}
private PositionOnTrack(int x, int y, Step direction) {
if (x > MAX_COORDINATE || x < 0) {
throw new IllegalArgumentException("x=" + x);
}
if (y > MAX_COORDINATE || y < 0) {
throw new IllegalArgumentException("y=" + y);
}
this.x = x;
this.y = y;
this.cameFrom = direction;
}
/**
* @return The direction the entity came from.
*/
public Step cameFrom() {
return cameFrom;
}
@Override
public boolean equals(Object o) {
if (null == o) {
return false;
}
if (o instanceof PositionOnTrack) {
PositionOnTrack other = (PositionOnTrack) o;
if (other.cameFrom() == this.cameFrom()
&& other.getX() == this.getX()
&& other.getY() == this.getY()) {
return true;
}
return false;
}
return false;
}
/**
* @return The direction the entity is facing.
*/
public Step facing() {
return cameFrom.getOpposite();
}
/**
* @return the position on the track which is in the opposite direction.
*/
public PositionOnTrack getOpposite() {
int newX = this.getX() - this.cameFrom.deltaX;
int newY = this.getY() - this.cameFrom.deltaY;
Step newDirection = this.cameFrom.getOpposite();
return createComingFrom(newX, newY, newDirection);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public int hashCode() {
int result;
result = x;
result = 29 * result + y;
result = 29 * result + cameFrom.hashCode();
return result;
}
public void setCameFrom(Step v) {
this.cameFrom = v;
}
public void setFacing(Step v) {
this.cameFrom = v.getOpposite();
}
public void setValuesFromInt(int i) {
x = i & MAX_COORDINATE;
int shiftedY = i & (MAX_COORDINATE << BITS_FOR_COORDINATE);
y = shiftedY >> BITS_FOR_COORDINATE;
int shiftedDirection = i & (MAX_DIRECTION << (2 * BITS_FOR_COORDINATE));
int directionAsInt = shiftedDirection >> (2 * BITS_FOR_COORDINATE);
cameFrom = Step.getInstance(directionAsInt);
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void move(Step step) {
this.x += step.deltaX;
this.y += step.deltaY;
this.cameFrom = step.getOpposite();
}
/**
* @return an integer representing this PositionOnTrack object
*/
public int toInt() {
int i = x | (y << BITS_FOR_COORDINATE);
int directionAsInt = cameFrom.getID();
int shiftedDirection = (directionAsInt << (2 * BITS_FOR_COORDINATE));
i = i | shiftedDirection;
return i;
}
public static int toInt(int x, int y) {
int i = x | (y << BITS_FOR_COORDINATE);
return i;
}
@Override
public String toString() {
String s = "PositionOnTrack: " + x + ", " + y + " facing "
+ cameFrom.getOpposite().toString();
return s;
}
}
Methods:
MethodJavadoc
cameFrom/**
createComingFrom/**
createFacing
facing/**
fromInts
getOpposite/**
getX
getY
move
setCameFrom
setFacing
setValuesFromInt
setX
setY
toInt
toInt/**
toInts
jfreerails.world.common.Step
Javadoc:
/** * This class represents a movement from a tile to any one of the surrounding * eight tiles. * * @author Luke */
Source code:
/**
* This class represents a movement from a tile to any one of the surrounding
* eight tiles.
*
* @author Luke
*/
@jfreerails.util.InstanceControlled
final public class Step implements FlatTrackTemplate {
private static final long serialVersionUID = 3256444698640921912L;
public static final int TILE_DIAMETER = Constants.TILE_SIZE;
public static final double TILE_DIAGONAL = StrictMath.hypot(TILE_DIAMETER,
TILE_DIAMETER);
/** North. */
public static final Step NORTH;
/** West. */
public static final Step WEST;
/** South East. */
public static final Step SOUTH_EAST;
/** North-East. */
public static final Step NORTH_EAST;
/** East. */
public static final Step EAST;
/** South. */
public static final Step SOUTH;
/** South West. */
public static final Step SOUTH_WEST;
/** North West. */
public static final Step NORTH_WEST;
/**
* A 3x3 array of OneTileMoveVectors, representing vectors to eight adjacent
* tiles plus a zero-distance vector.
*/
private static final Step[][] vectors;
/**
* Another array of OneTileMoveVectors representing the 8 compass directions
* going clockwise from North.
*/
private static Step[] list;
static {
vectors = setupVectors();
NORTH = getInstance(0, -1);
WEST = getInstance(-1, 0);
SOUTH_EAST = getInstance(1, 1);
NORTH_EAST = getInstance(1, -1);
EAST = getInstance(1, 0);
SOUTH = getInstance(0, 1);
SOUTH_WEST = getInstance(-1, 1);
NORTH_WEST = getInstance(-1, -1);
list = new Step[8];
list[0] = NORTH;
list[1] = NORTH_EAST;
list[2] = EAST;
list[3] = SOUTH_EAST;
list[4] = SOUTH;
list[5] = SOUTH_WEST;
list[6] = WEST;
list[7] = NORTH_WEST;
}
private static Step[][] setupVectors() {
int t = 1;
Step[][] tvectors = new Step[3][3];
for (int y = -1; y <= 1; y++) {
for (int x = -1; x <= 1; x++) {
if ((0 != x) || (0 != y)) {
tvectors[x + 1][y + 1] = new Step(x, y, t);
}
t = t << 1;
}
}
return tvectors;
}
public static ImPoint move(ImPoint p, Step... path) {
int x = p.x;
int y = p.y;
for (Step v : path) {
x += v.deltaX;
y += v.deltaY;
}
return new ImPoint(x, y);
}
/** The X and Y components of the vector. */
public final int deltaX;
/** The X and Y components of the vector. */
public final int deltaY;
private final int flatTrackTemplate;
private final double length;
/** Returns the X component of the vector. */
public int getDx() {
return deltaX;
}
/** Returns the Y component of the vector. */
public int getDy() {
return deltaY;
}
/**
* Returns a new oneTileMoveVector whose direction is opposite to that the
* current one.
*
* @return A oneTileMoveVector.
*/
public Step getOpposite() {
return getInstance(this.deltaX * -1, this.deltaY * -1);
}
/**
* Returns the name of the vector. E.g. "north-east"
*
* @return the name.
*/
@Override
public String toString() {
String name;
switch (deltaY) {
case 1:
name = " south";
break;
case -1:
name = " north";
break;
default:
name = "";
break;
}
switch (deltaX) {
case 1:
name += " east";
break;
case -1:
name += " west";
break;
default:
break;
}
return name;
}
public String toAbrvString() {
String name;
switch (deltaY) {
case 1:
name = "s";
break;
case -1:
name = "n";
break;
default:
name = "";
break;
}
switch (deltaX) {
case 1:
name += "e";
break;
case -1:
name += "w";
break;
default:
break;
}
return name;
}
/**
* Create a new OneTileMoveVector. N.B Private constructor to enforce enum
* property, use getInstance(x,y) instead. Pass values for delta X and Y:
* they must be in the range -1 to 1 and cannot both be equal to 0.
*
* @param x
* Tile coordinate.
* @param y
* Tile coordinate
* @param t
* an integer representing the track template this vector
* corresponds to.
*/
private Step(int x, int y, int t) {
deltaX = x;
deltaY = y;
flatTrackTemplate = t;
length = (x * y) == 0 ? TILE_DIAMETER : TILE_DIAGONAL;
}
public static Step getInstance(int number) {
return list[number];
}
public static boolean checkValidity(ImPoint a, ImPoint b) {
int dx = b.x - a.x;
int dy = b.y - a.y;
return checkValidity(dx, dy);
}
public static Step getInstance(int dx, int dy) {
if ((((dx < -1) || (dx > 1)) || ((dy < -1) || (dy > 1)))
|| ((dx == 0) && (dy == 0))) {
throw new IllegalArgumentException(
dx
+ " and "
+ dy
+ ": The values passed both must be integers in the range -1 to 1, and not both equal 0.");
}
return vectors[dx + 1][dy + 1];
}
/**
* Returns true if the values passed could be used to create a valid vector.
*/
public static boolean checkValidity(int x, int y) {
if ((((x < -1) || (x > 1)) || ((y < -1) || (y > 1)))
|| ((x == 0) && (y == 0))) {
return false;
}
return true;
}
public ImPoint createRelocatedPoint(ImPoint from) {
return new ImPoint(from.x + deltaX, from.y + deltaY);
}
public boolean contains(FlatTrackTemplate ftt) {
if (ftt.get9bitTemplate() == this.flatTrackTemplate) {
return true;
}
return false;
}
public int get9bitTemplate() {
return flatTrackTemplate;
}
/**
* @return a copy of the list of 8 OneTileMoveVectors going clockwise from
* North.
*/
public static Step[] getList() {
return list.clone(); // defensive copy.
}
/**
* @return the length of this vector. Each tile is 100 units x 100 units.
*/
public double getLength() {
return length;
}
/**
*
* @return compass bearing in radians.
*/
public double getDirection() {
int i = 0;
while (this != list[i]) {
i++;
}
return 2 * Math.PI / 8 * i;
}
/**
* @return a number representing the compass point this vector indicates,
* with 0 representing North, 1 NorthEast, 2 East and so on.
*/
public int getID() {
int i = 0;
while (this != list[i]) {
i++;
}
return i;
}
private Object readResolve() throws ObjectStreamException {
return Step.getInstance(this.deltaX, this.deltaY);
}
/**
* @return the OneTileMoveVector nearest in orientation to the specified dx,
* dy
*/
public static Step getNearestVector(int dx, int dy) {
if (0 == dx * dy) {
if (dx > 0) {
return EAST;
} else if (dx != 0) {
return WEST;
} else if (dy > 0) {
return SOUTH;
} else {
return NORTH;
}
}
double gradient = dy;
gradient = gradient / dx;
double B = 2;
double A = 0.5;
double C = -2;
double D = -0.5;
if (gradient > B) {
if (dy < 0) {
return NORTH;
}
return SOUTH;
} else if (gradient > A) {
if (dy > 0) {
return SOUTH_EAST;
}
return NORTH_WEST;
} else if (gradient > D) {
if (dx > 0) {
return EAST;
}
return WEST;
} else if (gradient > C) {
if (dx < 0) {
return SOUTH_WEST;
}
return NORTH_EAST;
} else {
if (dy > 0) {
return SOUTH;
}
return NORTH;
}
}
public boolean isDiagonal() {
return 0 != deltaX * deltaY;
}
public int get8bitTemplate() {
return 1 << this.getID();
}
}
Methods:
MethodJavadoc
checkValidity
checkValidity/**
contains
createRelocatedPoint
get8bitTemplate
get9bitTemplate
getDirection/**
getDx/** Returns the X component of the vector. */
getDy/** Returns the Y component of the vector. */
getID/**
getInstance
getInstance
getLength/**
getList/**
getNearestVector/**
getOpposite/**
isDiagonal
move
readResolve
setupVectors
toAbrvString
jfreerails.world.player.FreerailsPrincipal
Javadoc:
/** * This interface identifies a principal. This interface may be extended in the * future in order to provide faster lookups, rather than using name * comparisons. * * A principal represents an entity which can view or alter the game world. A * principal usually corresponds to a player's identity, but may also represent * an authoritative server, or a another game entity such as a corporation. * All entities which may own game world objects must be represented by a * principal. * * @author rob */
Source code:
/**
* This interface identifies a principal. This interface may be extended in the
* future in order to provide faster lookups, rather than using name
* comparisons.
*
* A principal represents an entity which can view or alter the game world. A
* principal usually corresponds to a player's identity, but may also represent
* an authoritative server, or a another game entity such as a corporation.
* All entities which may own game world objects must be represented by a
* principal.
*
* @author rob
*/
public abstract class FreerailsPrincipal implements Principal,
FreerailsSerializable {
private static final long serialVersionUID = -1689464560504992959L;
private int worldIndex;
public FreerailsPrincipal(int worldIndex) {
this.worldIndex = worldIndex;
}
/**
* returns -1 if it's not a player
* @return the index in the world structures
*/
public int getWorldIndex() {
return worldIndex;
}
}
Methods:
MethodJavadoc
getWorldIndex/**
jfreerails.world.player.Player
Javadoc:
/** * Represents a player within the game. The player model is such that a user can * start a client, create a new player on the server and start playing. They can * disconnect from the server, which may continue running with other players * still active. The server can then save the list of players and be stopped and * restarted again, the clients can then authenticate themselves to the server * and continue their sessions where they left off. * * XXX the player is only authenticated when the connection is opened, and * subsequent exchanges are not authenticated. * * TODO implement a more complete authentication system using certificates * rather than public keys. * * @author rtuck99@users.sourceforge.net */
Source code:
/**
* Represents a player within the game. The player model is such that a user can
* start a client, create a new player on the server and start playing. They can
* disconnect from the server, which may continue running with other players
* still active. The server can then save the list of players and be stopped and
* restarted again, the clients can then authenticate themselves to the server
* and continue their sessions where they left off.
*
* XXX the player is only authenticated when the connection is opened, and
* subsequent exchanges are not authenticated.
*
* TODO implement a more complete authentication system using certificates
* rather than public keys.
*
* @author rtuck99@users.sourceforge.net
*/
public class Player implements FreerailsSerializable {
private static final long serialVersionUID = 1;
/** A FreerailsPrincipal that is not a player. */
private static class WorldPrincipal extends FreerailsPrincipal {
private static final long serialVersionUID = 1;
private final String principalName;
public WorldPrincipal(String name) {
super(-1);
this.principalName = name;
}
public String getName() {
return principalName;
}
@Override
public String toString() {
return principalName;
}
@Override
public int hashCode() {
return principalName.hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof WorldPrincipal)) {
return false;
}
return (principalName.equals(((WorldPrincipal) o).principalName));
}
}
private FreerailsPrincipal principal;
/**
* This Principal can be granted all permissions.
*/
public static final FreerailsPrincipal AUTHORITATIVE = new WorldPrincipal(
"Authoritative Server");
/**
* This Principal has no permissions.
*/
public static final FreerailsPrincipal NOBODY = new WorldPrincipal("Nobody");
/**
* Name of the player.
*/
private final String name;
/**
* Used by the client to generate a player with a particular name.
*/
public Player(String name) {
this.name = name;
KeyPairGenerator kpg;
/* generate our key pair */
try {
kpg = KeyPairGenerator.getInstance("DSA");
kpg.initialize(1024);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/**
* Used by the server to generate a player with a particular name and public
* key.
*
*/
public Player(String name, int id) {
this.name = name;
// this.publicKey = publicKey;
// privateData = new PrivateData();
this.principal = new PlayerPrincipal(id, name);
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (!(o instanceof Player)) {
return false;
}
// return (name.equals(((Player) o).name) && keysEqual);
return (name.equals(((Player) o).name));
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return name;
}
public String getName() {
return name;
}
/**
* TODO save this player's private data so that they can be re-connected to
* the server at a later point in time.
*/
public void saveSession(ObjectOutputStream out) throws IOException {
// out.writeObject(privateData);
}
/**
* Called by the client to reconstitute the data from a saved game.
*/
public void loadSession(ObjectInputStream in) throws IOException {
// try {
// privateData = (PrivateData) in.readObject();
// } catch (ClassNotFoundException e) {
// throw new IOException("Couldn't find class:" + e);
// }
}
public FreerailsPrincipal getPrincipal() {
return principal;
}
}
Methods:
MethodJavadoc
getName
getPrincipal
loadSession/**
saveSession/**
jfreerails.world.player.PlayerPrincipal
Javadoc:
/** * FreerailsPrincipal that is a player in the game. * * @author rob */
Source code:
/**
* FreerailsPrincipal that is a player in the game.
*
* @author rob
*/
public class PlayerPrincipal extends FreerailsPrincipal {
private static final long serialVersionUID = 3257563997099537459L;
private final int id;
private final String name;
public PlayerPrincipal(int id, String name) {
super(id);
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
@Override
public int hashCode() {
return id;
}
@Override
public String toString() {
return "Player " + id;
}
/**
* @return an integer unique to this PlayerPrincipal
*/
public int getId() {
return id;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof PlayerPrincipal)) {
return false;
}
return id == ((PlayerPrincipal) o).id;
}
}
Methods:
MethodJavadoc
getId/**
getName
jfreerails.world.station.ConvertedAtStation
Javadoc:
/** * Records which cargos are converted to other cargos at a station. * * @author Luke */
Source code:
/**
* Records which cargos are converted to other cargos at a station.
*
* @author Luke
*/
public class ConvertedAtStation implements FreerailsSerializable {
private static final long serialVersionUID = 3690754012076978231L;
private static final int NOT_CONVERTED = Integer.MIN_VALUE;
private final ImInts convertedTo;
public ConvertedAtStation(int[] convertedTo) {
this.convertedTo = new ImInts(convertedTo);
}
public static ConvertedAtStation emptyInstance(int numberOfCargoTypes) {
int[] convertedTo = emptyConversionArray(numberOfCargoTypes);
return new ConvertedAtStation(convertedTo);
}
public static int[] emptyConversionArray(int numberOfCargoTypes) {
int[] convertedTo = new int[numberOfCargoTypes];
for (int i = 0; i < numberOfCargoTypes; i++) {
convertedTo[i] = NOT_CONVERTED;
}
return convertedTo;
}
public boolean isCargoConverted(int cargoNumber) {
if (NOT_CONVERTED == convertedTo.get(cargoNumber)) {
return false;
}
return true;
}
public int getConversion(int cargoNumber) {
return convertedTo.get(cargoNumber);
}
@Override
public int hashCode() {
int result = 0;
for (int i = 0; i < convertedTo.size(); i++) {
result = 29 * result + convertedTo.get(i);
}
return result;
}
@Override
public boolean equals(Object o) {
if (o instanceof ConvertedAtStation) {
ConvertedAtStation test = (ConvertedAtStation) o;
if (this.convertedTo.size() != test.convertedTo.size()) {
return false;
}
for (int i = 0; i < convertedTo.size(); i++) {
if (convertedTo.get(i) != test.convertedTo.get(i)) {
return false;
}
}
return true;
}
return false;
}
}
Methods:
MethodJavadoc
emptyConversionArray
emptyInstance
getConversion
isCargoConverted
jfreerails.world.station.Demand4Cargo
Javadoc:
/** * This class represents the demand for cargo at a station. * * @author Luke */
Source code:
/**
* This class represents the demand for cargo at a station.
*
* @author Luke
*/
public class Demand4Cargo implements FreerailsSerializable {
private static final long serialVersionUID = 3257565088071038009L;
private final ImInts demand;
public Demand4Cargo(boolean[] demandArray) {
demand = ImInts.fromBoolean(demandArray);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Demand4Cargo))
return false;
final Demand4Cargo demandAtStation = (Demand4Cargo) o;
if (!demand.equals(demandAtStation.demand))
return false;
return true;
}
@Override
public int hashCode() {
int result = 0;
for (int i = 0; i < demand.size(); i++) {
result = 29 * result + demand.get(i);
}
return result;
}
public boolean isCargoDemanded(int cargoNumber) {
return demand.get(cargoNumber) == 1;
}
}
Methods:
MethodJavadoc
isCargoDemanded
jfreerails.world.station.PlannedTrain
Javadoc:
/** * This class represents the blue print for what an engine shop is producing. * * @author Luke * */
Source code:
/**
* This class represents the blue print for what an engine shop is producing.
*
* @author Luke
*
*/
public class PlannedTrain implements FreerailsSerializable {
private static final long serialVersionUID = 3545515106038592057L;
private final int engineType;
private final ImInts wagonTypes;
public PlannedTrain(int e, int[] wagons) {
engineType = e;
wagonTypes = new ImInts(wagons);
}
@Override
public int hashCode() {
return engineType;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof PlannedTrain))
return false;
final PlannedTrain productionAtEngineShop = (PlannedTrain) o;
if (engineType != productionAtEngineShop.engineType)
return false;
if (!wagonTypes.equals(productionAtEngineShop.wagonTypes))
return false;
return true;
}
public int getEngineType() {
return engineType;
}
public ImInts getWagonTypes() {
return wagonTypes;
}
@Override
public String toString() {
return "engine type: " + this.engineType + ", with "
+ wagonTypes.size() + "wagons";
}
}
Methods:
MethodJavadoc
getEngineType
getWagonTypes
jfreerails.world.station.StationModel
Javadoc:
/** * This class represents a station. * * @author Luke * */
Source code:
/**
* This class represents a station.
*
* @author Luke
*
*/
public class StationModel implements FreerailsSerializable {
private static final long serialVersionUID = 3256442503979874355L;
public final int x;
public final int y;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof StationModel))
return false;
final StationModel stationModel = (StationModel) o;
if (cargoBundleNumber != stationModel.cargoBundleNumber)
return false;
if (x != stationModel.x)
return false;
if (y != stationModel.y)
return false;
if (converted != null ? !converted.equals(stationModel.converted)
: stationModel.converted != null)
return false;
if (demand != null ? !demand.equals(stationModel.demand)
: stationModel.demand != null)
return false;
if (!name.equals(stationModel.name))
return false;
if (production != null ? !production.equals(stationModel.production)
: stationModel.production != null)
return false;
if (supply != null ? !supply.equals(stationModel.supply)
: stationModel.supply != null)
return false;
return true;
}
private final String name;
private final SupplyAtStation supply;
private final Demand4Cargo demand;
private final ConvertedAtStation converted;
private final int cargoBundleNumber;
/** What this station is building. */
private final ImList<PlannedTrain> production;
public ConvertedAtStation getConverted() {
return converted;
}
@Override
public int hashCode() {
int result;
result = x;
result = 29 * result + y;
result = 29 * result + (name != null ? name.hashCode() : 0);
result = 29 * result + (supply != null ? supply.hashCode() : 0);
result = 29 * result + (demand != null ? demand.hashCode() : 0);
result = 29 * result + (converted != null ? converted.hashCode() : 0);
result = 29 * result + cargoBundleNumber;
result = 29 * result + production.size();
return result;
}
public StationModel(StationModel s, ConvertedAtStation converted) {
this.converted = converted;
this.cargoBundleNumber = s.cargoBundleNumber;
this.demand = s.demand;
this.name = s.name;
this.production = s.production;
this.supply = s.supply;
this.x = s.x;
this.y = s.y;
}
public StationModel(int x, int y, String stationName,
int numberOfCargoTypes, int cargoBundle) {
this.name = stationName;
this.x = x;
this.y = y;
production = new ImList<PlannedTrain>();
supply = new SupplyAtStation(new int[numberOfCargoTypes]);
demand = new Demand4Cargo(new boolean[numberOfCargoTypes]);
converted = ConvertedAtStation.emptyInstance(numberOfCargoTypes);
cargoBundleNumber = cargoBundle;
}
public StationModel() {
this.name = "No name";
x = 0;
y = 0;
this.demand = new Demand4Cargo(new boolean[0]);
this.supply = new SupplyAtStation(new int[0]);
this.converted = new ConvertedAtStation(new int[0]);
production = new ImList<PlannedTrain>();
this.cargoBundleNumber = 0;
}
public String getStationName() {
return name;
}
public int getStationX() {
return x;
}
public int getStationY() {
return y;
}
public ImPoint getLocation(){
return new ImPoint(x, y);
}
public ImList<PlannedTrain> getProduction() {
return production;
}
public StationModel(StationModel s, ImList<PlannedTrain> production) {
this.production = production;
this.demand = s.demand;
this.cargoBundleNumber = s.cargoBundleNumber;
this.converted = s.converted;
this.name = s.name;
this.supply = s.supply;
this.x = s.x;
this.y = s.y;
}
public Demand4Cargo getDemand() {
return demand;
}
public SupplyAtStation getSupply() {
return supply;
}
public StationModel(StationModel s, Demand4Cargo demand) {
this.demand = demand;
this.cargoBundleNumber = s.cargoBundleNumber;
this.converted = s.converted;
this.name = s.name;
this.production = s.production;
this.supply = s.supply;
this.x = s.x;
this.y = s.y;
}
public StationModel(StationModel s, SupplyAtStation supply) {
this.supply = supply;
this.demand = s.demand;
this.cargoBundleNumber = s.cargoBundleNumber;
this.converted = s.converted;
this.name = s.name;
this.production = s.production;
this.x = s.x;
this.y = s.y;
}
public int getCargoBundleID() {
return cargoBundleNumber;
}
}
Methods:
MethodJavadoc
getCargoBundleID
getConverted
getDemand
getLocation
getProduction
getStationName
getStationX
getStationY
getSupply/**
jfreerails.world.station.SupplyAtStation
Javadoc:
/** * This class represents the supply at a station. * * @author Luke */
Source code:
/**
* This class represents the supply at a station.
*
* @author Luke
*/
public class SupplyAtStation implements FreerailsSerializable {
private static final long serialVersionUID = 4049918272826847286L;
private final ImInts supply;
public SupplyAtStation(int[] cargoWaiting) {
supply = new ImInts(cargoWaiting);
}
/**
* Returns the number of car loads of the specified cargo that the station
* supplies per year.
*/
public int getSupply(int cargoType) {
return supply.get(cargoType);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof SupplyAtStation))
return false;
final SupplyAtStation supplyAtStation = (SupplyAtStation) o;
if (!supply.equals(supplyAtStation.supply))
return false;
return true;
}
@Override
public int hashCode() {
return supply.hashCode();
}
}
Methods:
MethodJavadoc
getSupply/**
jfreerails.world.terrain.CityModel
Javadoc:
/** * A city. * * @author Luke */
Source code:
/**
* A city.
*
* @author Luke
*/
public class CityModel implements FreerailsSerializable {
private static final long serialVersionUID = 3256720697500709428L;
private final String name;
private final int x;
private final int y;
public CityModel(String s, int xx, int yy) {
name = s;
x = xx;
y = yy;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof CityModel))
return false;
final CityModel cityModel = (CityModel) o;
if (x != cityModel.x)
return false;
if (y != cityModel.y)
return false;
if (!name.equals(cityModel.name))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = name.hashCode();
result = 29 * result + x;
result = 29 * result + y;
return result;
}
public String getCityName() {
return name;
}
public int getCityX() {
return x;
}
public int getCityY() {
return y;
}
public ImPoint getLocation(){
return new ImPoint(x, y);
}
@Override
public String toString() {
return name+" "+x+", "+y;
}
}
Methods:
MethodJavadoc
getCityName
getCityX
getCityY
getLocation
jfreerails.world.terrain.Consumption
Javadoc:
/** * This class represents the demand for a certain cargo for consumption. * * @author Luke * */
Source code:
/**
* This class represents the demand for a certain cargo for consumption.
*
* @author Luke
*
*/
public class Consumption implements FreerailsSerializable {
private static final long serialVersionUID = 3258133565631051064L;
private final int cargoType;
/**
* The number of tiles that must be within the station radius before the
* station demands the cargo.
*/
private final int prerequisite;
public Consumption(int ct, int pq) {
cargoType = ct;
prerequisite = pq; // default value.
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Consumption))
return false;
final Consumption consumption = (Consumption) o;
if (cargoType != consumption.cargoType)
return false;
if (prerequisite != consumption.prerequisite)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = cargoType;
result = 29 * result + prerequisite;
return result;
}
public int getCargoType() {
return cargoType;
}
public int getPrerequisite() {
return prerequisite;
}
}
Methods:
MethodJavadoc
getCargoType
getPrerequisite
jfreerails.world.terrain.Conversion
Javadoc:
/** * This class represents the conversion of one cargo type to another one a tile. * * @author Luke * */
Source code:
/**
* This class represents the conversion of one cargo type to another one a tile.
*
* @author Luke
*
*/
public class Conversion implements FreerailsSerializable {
private static final long serialVersionUID = 3546356219414853689L;
private final int input;
private final int output;
public Conversion(int in, int out) {
input = in;
output = out;
}
public int getInput() {
return input;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Conversion))
return false;
final Conversion conversion = (Conversion) o;
if (input != conversion.input)
return false;
if (output != conversion.output)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = input;
result = 29 * result + output;
return result;
}
public int getOutput() {
return output;
}
}
Methods:
MethodJavadoc
getInput
getOutput
jfreerails.world.terrain.NullTerrainType
Javadoc:
/** * Represents a null terrain type, serving as a default or placeholder implementation. * This singleton class provides empty or default values for all terrain type properties, * ensuring compatibility with the TerrainType interface when no specific terrain type is applicable. * * @author Your Name * @see TerrainType */
Source code:
@InstanceControlled
public class NullTerrainType implements TerrainType {
public static final TerrainType INSTANCE = new NullTerrainType();
private NullTerrainType() {
}
private static final long serialVersionUID = 3834874680581369912L;
public ImList<Production> getProduction() {
return new ImList<Production>();
}
public ImList<Consumption> getConsumption() {
return new ImList<Consumption>();
}
public ImList<Conversion> getConversion() {
return new ImList<Conversion>();
}
public String getTerrainTypeName() {
return "null";
}
public Category getCategory() {
return Category.Country;
}
public int getRGB() {
return 0;
}
public int getRightOfWay() {
return 0;
}
public String getDisplayName() {
return "";
}
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
public Money getBuildCost() {
return new Money(0);
}
}
Methods:
MethodJavadoc
getBuildCost
getCategory
getConsumption
getConversion
getDisplayName
getProduction
getRGB
getRightOfWay
getTerrainTypeName
readResolve
jfreerails.world.terrain.Production
Javadoc:
/** * This class represents the production of a raw material on a tile. * * @author Luke * */
Source code:
/**
* This class represents the production of a raw material on a tile.
*
* @author Luke
*
*/
public class Production implements FreerailsSerializable {
private static final long serialVersionUID = 3258125847641536052L;
private final int cargoType;
/** The number of units per year (40 units = 1 car load). */
private final int rate;
public Production(int type, int r) {
cargoType = type;
rate = r;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Production))
return false;
final Production production = (Production) o;
if (cargoType != production.cargoType)
return false;
if (rate != production.rate)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = cargoType;
result = 29 * result + rate;
return result;
}
public int getCargoType() {
return cargoType;
}
public int getRate() {
return rate;
}
}
Methods:
MethodJavadoc
getCargoType
getRate
jfreerails.world.terrain.TerrainTile
Javadoc:
/** * Defines the interface of a terrain tile. * * @author Luke */
Source code:
/**
* Defines the interface of a terrain tile.
*
* @author Luke
*/
public interface TerrainTile extends FreerailsSerializable {
int getTerrainTypeID();
}
Methods:
MethodJavadoc
getTerrainTypeID
jfreerails.world.terrain.TerrainType
Javadoc:
/** * Defines the methods to access the properties of a type of terrains. * * * @author Luke */
Source code:
/**
* Defines the methods to access the properties of a type of terrains.
*
*
* @author Luke
*/
public interface TerrainType extends FreerailsSerializable {
enum Category implements FreerailsSerializable {
Urban, River, Ocean, Hill, Country, Special, Industry, Resource
}
String getTerrainTypeName();
Category getCategory();
Money getBuildCost();
int getRightOfWay();
int getRGB();
ImList<Production> getProduction();
ImList<Consumption> getConsumption();
ImList<Conversion> getConversion();
String getDisplayName();
}
Methods:
MethodJavadoc
getBuildCost
getCategory
getConsumption
getConversion
getDisplayName/**
getProduction
getRGB
getRightOfWay
getTerrainTypeName
jfreerails.world.terrain.TileTypeImpl
Javadoc:
/** * Represents a type of terrain. * * @author Luke Lindsay 16 August 2001 */
Source code:
/**
* Represents a type of terrain.
*
* @author Luke Lindsay 16 August 2001
*/
final public class TileTypeImpl implements TerrainType {
private static final long serialVersionUID = 4049919380945253945L;
private final ImList<Consumption> consumption;
private final ImList<Conversion> conversion;
private final ImList<Production> production;
private final int rgb;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TileTypeImpl))
return false;
final TileTypeImpl tileType = (TileTypeImpl) o;
if (rgb != tileType.rgb)
return false;
if (rightOfWay != tileType.rightOfWay)
return false;
if (!consumption.equals(tileType.consumption))
return false;
if (!conversion.equals(tileType.conversion))
return false;
if (!production.equals(tileType.production))
return false;
if (!terrainCategory.equals(tileType.terrainCategory))
return false;
if (!terrainType.equals(tileType.terrainType))
return false;
if (tileBuildCost != null ? !tileBuildCost
.equals(tileType.tileBuildCost)
: tileType.tileBuildCost != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = consumption.hashCode();
result = 29 * result + conversion.hashCode();
result = 29 * result + production.hashCode();
result = 29 * result + rgb;
result = 29 * result + rightOfWay;
result = 29 * result + terrainCategory.hashCode();
result = 29 * result + terrainType.hashCode();
result = 29 * result
+ (tileBuildCost != null ? tileBuildCost.hashCode() : 0);
return result;
}
private final int rightOfWay;
private final TerrainType.Category terrainCategory;
private final String terrainType;
/**
* Cost to build a tile of this terrain type or null if this type is not
* buildable.
*/
private final Money tileBuildCost;
public TileTypeImpl(int rgb, TerrainType.Category terrainCategory,
String terrainType, int rightOfWay, Production[] production,
Consumption[] consumption, Conversion[] conversion,
int tileBuildCost) {
this.terrainType = terrainType;
this.terrainCategory = terrainCategory;
this.rgb = rgb;
this.rightOfWay = rightOfWay;
this.production = new ImList<Production>(production);
this.consumption = new ImList<Consumption>(consumption);
this.conversion = new ImList<Conversion>(conversion);
if (tileBuildCost > 0) {
this.tileBuildCost = new Money(tileBuildCost);
} else {
this.tileBuildCost = null;
}
}
/**
* Lets unit tests create terrain types without bothering with all the
* details.
*/
public TileTypeImpl(TerrainType.Category terrainCategory, String terrainType) {
this.terrainType = terrainType;
this.terrainCategory = terrainCategory;
this.rgb = 0;
this.rightOfWay = 0;
this.production = new ImList<Production>();
this.consumption = new ImList<Consumption>();
this.conversion = new ImList<Conversion>();
this.tileBuildCost = null;
}
public Money getBuildCost() {
return tileBuildCost;
}
public Category getCategory() {
return terrainCategory;
}
public ImList<Consumption> getConsumption() {
return consumption;
}
public ImList<Conversion> getConversion() {
return conversion;
}
/** Returns the name, replacing any underscores with spaces. */
public String getDisplayName() {
return terrainType.replace('_', ' ');
}
public ImList<Production> getProduction() {
return production;
}
/**
* @return The RGB value mapped to this terrain type.
*/
public int getRGB() {
return rgb;
}
public int getRightOfWay() {
return rightOfWay;
}
public String getTerrainTypeName() {
return terrainType;
}
}
Methods:
MethodJavadoc
getBuildCost
getCategory
getConsumption
getConversion
getDisplayName/** Returns the name, replacing any underscores with spaces. */
getProduction
getRGB/**
getRightOfWay
getTerrainTypeName
jfreerails.world.top.GameRules
Javadoc:
/** * Stores rules governing what players are allowed to do, for example whether * they can connect their track to the track of other players. * * @author Luke * */
Source code:
/**
* Stores rules governing what players are allowed to do, for example whether
* they can connect their track to the track of other players.
*
* @author Luke
*
*/
public class GameRules implements FreerailsSerializable {
private static final long serialVersionUID = 3258125847557978416L;
private final boolean canConnect2OtherRRTrack;
private final boolean mustConnect2ExistingTrack;
public static final GameRules DEFAULT_RULES = new GameRules(true, false);
public static final GameRules NO_RESTRICTIONS = new GameRules(false, true);
@Override
public int hashCode() {
int result;
result = (canConnect2OtherRRTrack ? 1 : 0);
result = 29 * result + (mustConnect2ExistingTrack ? 1 : 0);
return result;
}
private GameRules(boolean mustConnect, boolean canConnect2others) {
canConnect2OtherRRTrack = canConnect2others;
mustConnect2ExistingTrack = mustConnect;
}
public synchronized boolean isCanConnect2OtherRRTrack() {
return canConnect2OtherRRTrack;
}
public synchronized boolean isMustConnect2ExistingTrack() {
return mustConnect2ExistingTrack;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof GameRules)) {
return false;
}
GameRules test = (GameRules) obj;
return this.canConnect2OtherRRTrack == test.canConnect2OtherRRTrack
&& this.mustConnect2ExistingTrack == test.mustConnect2ExistingTrack;
}
}
Methods:
MethodJavadoc
isCanConnect2OtherRRTrack
isMustConnect2ExistingTrack
jfreerails.world.top.ITEM
Javadoc:
/** * <p> * This class provides a set of keys to access the items of which there can only * be one instance in the game world in the game world (for example, the current * time). * </P> * * <p> * It implements the typesafe enum pattern (see Bloch, <I>Effective Java</I> * item 21) * </p> * * @author Luke */
Source code:
/**
* <p>
* This class provides a set of keys to access the items of which there can only
* be one instance in the game world in the game world (for example, the current
* time).
* </P>
*
* <p>
* It implements the typesafe enum pattern (see Bloch, <I>Effective Java</I>
* item 21)
* </p>
*
* @author Luke
*/
@jfreerails.util.InstanceControlled
public class ITEM implements FreerailsSerializable {
private static final long serialVersionUID = 3257846593180151859L;
/** Maps key numbers to KEYs. */
private static final ITEM[] keys = new ITEM[getNumberOfKeys()];
// START OF KEYS
public static final ITEM CALENDAR = new ITEM();
public static final ITEM GAME_RULES = new ITEM();
public static final ITEM GAME_SPEED = new ITEM();
public static final ITEM ECONOMIC_CLIMATE = new ITEM();
// END OF KEYS
private static int numberOfKeys = 0;
private final int keyNumber;
private ITEM() {
this.keyNumber = numberOfKeys;
keys[keyNumber] = this;
numberOfKeys++;
}
static int getNumberOfKeys() {
return ITEM.class.getFields().length;
}
int getKeyID() {
return keyNumber;
}
private Object readResolve() throws ObjectStreamException {
return keys[this.keyNumber];
}
@Override
public String toString() {
return Utils.findConstantFieldName(this);
}
}
Methods:
MethodJavadoc
getKeyID
getNumberOfKeys
readResolve
jfreerails.world.top.ItemsTransactionAggregator
Javadoc:
/** * Adds up the number of assets. * * @author Luke * */
Source code:
/**
* Adds up the number of assets.
*
* @author Luke
*
*/
public class ItemsTransactionAggregator extends TransactionAggregator {
public static final int ANY_VALUE = Integer.MIN_VALUE;
private int type = ANY_VALUE;
private Transaction.Category category = null;
private int[] quantities;
private int quantityRunningTotal;
/**
* Stores the quantities and monetary values of a series of items.
*
* @author Luke
*
*/
public static class QuantitiesAndValues {
public int[] quantities;
public Money[] values;
}
public ItemsTransactionAggregator(ReadOnlyWorld w,
FreerailsPrincipal principal) {
super(w, principal);
}
/**
* Returns true if the transaction with the specified ID has an acceptable
* type and category.
*/
@Override
protected boolean condition(int transactionID) {
Transaction t = w.getTransaction(principal, transactionID);
if (!(t instanceof AddItemTransaction)) {
return false;
}
AddItemTransaction addItemTransaction = (AddItemTransaction) t;
boolean isTypeAcceptable = (type == ANY_VALUE)
|| (type == addItemTransaction.getType());
boolean isCategoryAcceptable = (category == null)
|| (category == addItemTransaction.getCategory());
return isCategoryAcceptable && isTypeAcceptable;
}
public int calculateQuantity() {
QuantitiesAndValues qnv = calculateQuantitiesAndValues();
return qnv.quantities[0];
}
public QuantitiesAndValues calculateQuantitiesAndValues() {
QuantitiesAndValues returnValue = new QuantitiesAndValues();
returnValue.values = super.calculateValues();
returnValue.quantities = this.quantities;
return returnValue;
}
@Override
protected void incrementRunningTotal(int transactionID) {
super.incrementRunningTotal(transactionID);
Transaction t = w.getTransaction(principal, transactionID);
AddItemTransaction addItemTransaction = (AddItemTransaction) t;
quantityRunningTotal += addItemTransaction.getQuantity();
}
@Override
protected void setTotalsArrayLength(int length) {
super.setTotalsArrayLength(length);
quantities = new int[length];
quantityRunningTotal = 0;
}
@Override
protected void storeRunningTotal(int timeIndex) {
/*
* Note, a negative sign since we are totalling the value of assets not
* their impact on the operating funds.
*/
monetaryTotals[timeIndex] = new Money(-runningTotal);
quantities[timeIndex] = quantityRunningTotal;
}
public Transaction.Category getCategory() {
return category;
}
public void setCategory(Transaction.Category category) {
this.category = category;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
Methods:
MethodJavadoc
calculateQuantitiesAndValues
calculateQuantity
condition/**
getCategory
getType
incrementRunningTotal
setCategory
setTotalsArrayLength
setType
storeRunningTotal
jfreerails.world.top.KEY
Javadoc:
/** * <p> * This class provides a set of keys to access the lists of elements in the game * world that are indexed by player. * </P> * * <p> * It implements the typesafe enum pattern (see Bloch, <I>Effective Java</I> * item 21) * </p> * * @author Luke */
Source code:
/**
* <p>
* This class provides a set of keys to access the lists of elements in the game
* world that are indexed by player.
* </P>
*
* <p>
* It implements the typesafe enum pattern (see Bloch, <I>Effective Java</I>
* item 21)
* </p>
*
* @author Luke
*/
@jfreerails.util.InstanceControlled
public class KEY implements FreerailsSerializable {
private static final long serialVersionUID = 3257572793275987001L;
/** Maps key numbers to KEYs. */
private static final KEY[] keys = new KEY[15];
// START OF KEYS
public static final KEY TRAINS = new KEY();
// public static final KEY TRAIN_POSITIONS = new KEY();
public static final KEY STATIONS = new KEY();
/** The cargo waiting at stations or carried by trains. */
public static final KEY CARGO_BUNDLES = new KEY();
public static final KEY TRAIN_SCHEDULES = new KEY();
// END OF KEYS
private static int numberOfKeys;
private final int keyNumber;
private KEY() {
this.keyNumber = numberOfKeys;
keys[keyNumber] = this;
numberOfKeys++;
}
static int getNumberOfKeys() {
return numberOfKeys;
}
int getKeyID() {
return keyNumber;
}
private Object readResolve() throws ObjectStreamException {
return keys[this.keyNumber];
}
@Override
public String toString() {
return Utils.findConstantFieldName(this);
}
public static KEY getKey(int keyNum) {
return keys[keyNum];
}
}
Methods:
MethodJavadoc
getKey
getKeyID
getNumberOfKeys
readResolve
jfreerails.world.top.MapFixtureFactory
Javadoc:
/** * This class is used to generate fixtures for Junit tests. * * @author Luke * */
Source code:
/**
* This class is used to generate fixtures for Junit tests.
*
* @author Luke
*
*/
public class MapFixtureFactory {
/** Only subclasses should use these constants. */
public static final Player TEST_PLAYER = new Player("test player", 0);
public static final FreerailsPrincipal TEST_PRINCIPAL = TEST_PLAYER
.getPrincipal();
/**
* Returns a world object with a map of the specified size with the terrain
* and cargo types setup.
*/
public static World getWorld(int w, int h) {
FreerailsTile tile = FreerailsTile.getInstance(0);
World world = new WorldImpl(w, h);
generateTerrainTypesList(world);
generateCargoTypesList(world);
for (int x = 0; x < w; x++) {
for (int y = 0; y < w; y++) {
world.setTile(x, y, tile);
}
}
return world;
}
public static void generateTrackRuleList(World world) {
TrackRule[] trackRulesArray = new TrackRule[3];
TrackRuleProperties[] trackRuleProperties = new TrackRuleProperties[3];
LegalTrackConfigurations[] legalTrackConfigurations = new LegalTrackConfigurations[3];
LegalTrackPlacement[] legalTrackPlacement = new LegalTrackPlacement[3];
HashSet<TerrainType.Category> cannotBuildOnTheseTerrainTypes = new HashSet<TerrainType.Category>();
cannotBuildOnTheseTerrainTypes.add(TerrainType.Category.Ocean);
// 1st track type..
String[] trackTemplates0 = { "000010000", "010010000", "010010010",
"100111000", "001111000", "010110000", "100110000", "100011000" };
legalTrackConfigurations[0] = new LegalTrackConfigurations(-1,
trackTemplates0);
trackRuleProperties[0] = new TrackRuleProperties(1, false, "type0",
TrackRule.TrackCategories.track, 0, 0, 10, 0);
legalTrackPlacement[0] = new LegalTrackPlacement(
cannotBuildOnTheseTerrainTypes,
LegalTrackPlacement.PlacementRule.ANYWHERE_EXCEPT_ON_THESE);
trackRulesArray[0] = new TrackRuleImpl(trackRuleProperties[0],
legalTrackConfigurations[0], legalTrackPlacement[0]);
// 2nd track type..
String[] trackTemplates1 = { "000010000", "010010000", "010010010" };
legalTrackConfigurations[1] = new LegalTrackConfigurations(-1,
trackTemplates1);
trackRuleProperties[1] = new TrackRuleProperties(2, false, "type1",
TrackRule.TrackCategories.track, 0, 0, 20, 0);
legalTrackPlacement[1] = new LegalTrackPlacement(
cannotBuildOnTheseTerrainTypes,
LegalTrackPlacement.PlacementRule.ANYWHERE_EXCEPT_ON_THESE);
trackRulesArray[1] = new TrackRuleImpl(trackRuleProperties[1],
legalTrackConfigurations[1], legalTrackPlacement[1]);
// 3rd track type..
trackRuleProperties[2] = new TrackRuleProperties(3, false, "type2",
TrackRule.TrackCategories.track, 0, 0, 30, 0);
String[] trackTemplates2 = { "000010000" };
legalTrackConfigurations[2] = new LegalTrackConfigurations(-1,
trackTemplates2);
legalTrackPlacement[2] = new LegalTrackPlacement(
cannotBuildOnTheseTerrainTypes,
LegalTrackPlacement.PlacementRule.ANYWHERE_EXCEPT_ON_THESE);
trackRulesArray[2] = new TrackRuleImpl(trackRuleProperties[2],
legalTrackConfigurations[2], legalTrackPlacement[2]);
// Add track rules to world
for (int i = 0; i < trackRulesArray.length; i++) {
world.add(SKEY.TRACK_RULES, trackRulesArray[i]);
}
// Add the terrain types if necessary.
if (world.size(SKEY.TERRAIN_TYPES) == 0) {
generateTerrainTypesList(world);
}
}
/** Adds hard coded cargo types. */
public static void generateCargoTypesList(World world) {
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Mail", Categories.Mail));
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Passengers",
Categories.Passengers));
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Goods",
Categories.Fast_Freight));
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Steel",
Categories.Slow_Freight));
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Coal",
Categories.Bulk_Freight));
}
/** Adds hard coded terrain types. */
private static void generateTerrainTypesList(World world) {
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Country, "Grassland"));
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Urban, "City"));
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Resource, "Mine"));
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Industry, "Factory"));
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Ocean, "Ocean"));
}
}
Methods:
MethodJavadoc
generateCargoTypesList/** Adds hard coded cargo types. */
generateTerrainTypesList/** Adds hard coded terrain types. */
generateTrackRuleList
getWorld/**
jfreerails.world.top.NonNullElements
Javadoc:
/** * Iterates over one of the lists on the world object only returning non null * elements. * * @author Luke * */
Source code:
/**
* Iterates over one of the lists on the world object only returning non null
* elements.
*
* @author Luke
*
*/
public class NonNullElements implements WorldIterator {
private final KEY key;
private final SKEY skey;
private final ReadOnlyWorld w;
private final FreerailsPrincipal principal;
private int index = BEFORE_FIRST;
private int row = BEFORE_FIRST;
private int size = -1;
public NonNullElements(SKEY k, ReadOnlyWorld world) {
if (null == k) {
throw new NullPointerException();
}
if (null == world) {
throw new NullPointerException();
}
key = null;
principal = null;
skey = k;
w = world;
}
public NonNullElements(KEY k, ReadOnlyWorld world, FreerailsPrincipal p) {
key = k;
w = world;
principal = p;
skey = null;
if (null == k) {
throw new NullPointerException();
}
if (null == world) {
throw new NullPointerException();
}
if (null == p) {
throw new NullPointerException();
}
}
public boolean next() {
int nextIndex = index; // this is used to look ahead.
do {
nextIndex++;
if (nextIndex >= listSize()) {
return false;
}
} while (!testCondition(nextIndex));
row++;
index = nextIndex;
return true;
}
public void reset() {
index = -1;
row = -1;
size = -1;
}
public FreerailsSerializable getElement() {
return listGet(index);
}
private FreerailsSerializable listGet(int i) {
if (null == this.skey) {
return w.get(principal, key, i);
}
return w.get(skey, i);
}
private int listSize() {
if (null == this.skey) {
return w.size(principal, key);
}
return w.size(this.skey);
}
public int getIndex() {
return index;
}
public int getRowID() {
return row;
}
public int size() {
if (-1 == size) { // lazy loading, if we have already calculated the
// size don't do it again.
int tempSize = 0;
for (int i = 0; i < listSize(); i++) {
if (null != listGet(i)) {
tempSize++;
}
}
size = tempSize;
}
return size;
}
public boolean previous() {
int previousIndex = index; // this is used to look back.
do {
previousIndex--;
if (previousIndex < 0) {
return false;
}
} while (!testCondition(previousIndex));
row--;
index = previousIndex;
return true;
}
/** Moves the cursor to the specified index. */
public void gotoIndex(int i) {
int newRow = -1;
for (int j = 0; j < listSize(); j++) {
if (testCondition(j)) {
newRow++;
if (i == j) {
reset();
this.index = i;
this.row = newRow;
return;
}
}
}
throw new NoSuchElementException("Index:" + String.valueOf(i)
+ " Size:" + listSize() + " Row:" + newRow);
}
protected boolean testCondition(int i) {
return null != listGet(i);
}
public int getNaturalNumber() {
return getRowID() + 1;
}
public void gotoRow(int newRow) {
if (row == newRow) {
return;
}
if (row < newRow) {
while (row != newRow) {
next();
}
} else {
while (row != newRow) {
previous();
}
}
return;
}
public static int row2index(ReadOnlyWorld w, KEY key, FreerailsPrincipal p,
int row) {
int count = 0;
for (int i = 0; i < w.size(p, key); i++) {
if (w.get(p, key, i) != null) {
if (count == row) {
return i;
}
count++;
}
}
throw new NoSuchElementException(String.valueOf(row));
}
}
Methods:
MethodJavadoc
getElement
getIndex
getNaturalNumber
getRowID
gotoIndex/** Moves the cursor to the specified index. */
gotoRow/**
listGet
listSize
next
previous
reset
row2index
size
testCondition
jfreerails.world.top.ReadOnlyWorld
Javadoc:
/** * <p> * This interface defines a unified set of methods to access the elements that * make up the game world. The game world is composed of the following * specific-purpose collections into which one can put game world elements. * </p> * <ul> * A list of players. * </ul> * <ul> * A 2D grid - the map. * </ul> * <ul> * A series of lists that are accessible using the keys defined in {@link SKEY} * </ul> * <ul> * Another series of lists indexed by player and accessible using the keys * defined in {@link KEY} * </ul> * <ul> * A collection items accessible using the keys defined in {@link ITEM} * </ul> * <ul> * A list of financial transactions for each of the players * </ul> * <p> * Example: the following code gets player1's train #5. * </p> * <p> * <CODE>TrainModel t = (TrainModel)world.get(KEY.TRAINS, 5, player1);</CODE> * </p> * <p> * The motivation for accessing lists using keys is that one does not need to * add a new class or change the interface of the World class when a new list is * added. Instead one can just add a new entry to the class KEY. * </p> * <p> * Code that loops through lists should handle null values gracefully * </p> * * * @author Luke * @author Rob */
Source code:
/**
* <p>
* This interface defines a unified set of methods to access the elements that
* make up the game world. The game world is composed of the following
* specific-purpose collections into which one can put game world elements.
* </p>
* <ul>
* A list of players.
* </ul>
* <ul>
* A 2D grid - the map.
* </ul>
* <ul>
* A series of lists that are accessible using the keys defined in {@link SKEY}
* </ul>
* <ul>
* Another series of lists indexed by player and accessible using the keys
* defined in {@link KEY}
* </ul>
* <ul>
* A collection items accessible using the keys defined in {@link ITEM}
* </ul>
* <ul>
* A list of financial transactions for each of the players
* </ul>
* <p>
* Example: the following code gets player1's train #5.
* </p>
* <p>
* <CODE>TrainModel t = (TrainModel)world.get(KEY.TRAINS, 5, player1);</CODE>
* </p>
* <p>
* The motivation for accessing lists using keys is that one does not need to
* add a new class or change the interface of the World class when a new list is
* added. Instead one can just add a new entry to the class KEY.
* </p>
* <p>
* Code that loops through lists should handle null values gracefully
* </p>
*
*
* @author Luke
* @author Rob
*/
public interface ReadOnlyWorld extends FreerailsMutableSerializable {
boolean boundsContain(int x, int y);
boolean boundsContain(FreerailsPrincipal p, KEY k, int index);
boolean boundsContain(SKEY k, int index);
GameTime currentTime();
/**
* Returns the element mapped to the specified item.
*/
FreerailsSerializable get(ITEM item);
/**
* Returns the element at the specified position in the specified list.
*/
FreerailsSerializable get(FreerailsPrincipal p, KEY key, int index);
/**
* Returns the element at the specified position in the specified list.
*/
FreerailsSerializable get(SKEY key, int index);
ActivityIterator getActivities(FreerailsPrincipal p, int index);
Money getCurrentBalance(FreerailsPrincipal p);
int getID(FreerailsPrincipal p);
/**
* Returns the height of the map in tiles.
*/
int getMapHeight();
/**
* Returns the width of the map in tiles.
*/
int getMapWidth();
int getNumberOfPlayers();
int getNumberOfTransactions(FreerailsPrincipal p);
int getNumberOfActiveEntities(FreerailsPrincipal p);
Player getPlayer(int i);
/**
* Returns the tile at the specified position on the map.
*/
FreerailsSerializable getTile(int x, int y);
Transaction getTransaction(FreerailsPrincipal p, int i);
GameTime getTransactionTimeStamp(FreerailsPrincipal p, int i);
public Pair<Transaction, GameTime> getTransactionAndTimeStamp(
FreerailsPrincipal p, int i);
boolean isPlayer(FreerailsPrincipal p);
/**
* Returns the number of elements in the specified list.
*/
int size(FreerailsPrincipal p, KEY key);
/**
* Returns the number of elements in the specified list.
*/
int size(SKEY key);
/**
* Returns number of active entities belonging to the specified principal.
*/
int size(FreerailsPrincipal p);
}
Methods:
MethodJavadoc
boundsContain
boundsContain
boundsContain
currentTime
get/**
get/**
get/**
getActivities
getCurrentBalance
getID
getMapHeight/**
getMapWidth/**
getNumberOfActiveEntities
getNumberOfPlayers
getNumberOfTransactions
getPlayer
getTile/**
getTransaction
getTransactionAndTimeStamp/**
getTransactionTimeStamp
isPlayer
size/**
size/**
size/**
jfreerails.world.top.SKEY
Javadoc:
/** * <p> * This class provides a set of keys to access the lists of elements in the game * world that are shared by all players. * </P> * * <p> * It implements the typesafe enum pattern (see Bloch, <I>Effective Java</I> * item 21) * </p> * * @author Luke */
Source code:
/**
* <p>
* This class provides a set of keys to access the lists of elements in the game
* world that are shared by all players.
* </P>
*
* <p>
* It implements the typesafe enum pattern (see Bloch, <I>Effective Java</I>
* item 21)
* </p>
*
* @author Luke
*/
@jfreerails.util.InstanceControlled
public class SKEY implements FreerailsSerializable {
private static final long serialVersionUID = 3257847679739506737L;
/** Maps key numbers to KEYs. */
private static final SKEY[] keys = new SKEY[getNumberOfKeys()];
// START OF KEYS
public static final SKEY TERRAIN_TYPES = new SKEY();
public static final SKEY WAGON_TYPES = new SKEY();
public static final SKEY CARGO_TYPES = new SKEY();
public static final SKEY CITIES = new SKEY();
public static final SKEY ENGINE_TYPES = new SKEY();
public static final SKEY TRACK_RULES = new SKEY();
// END OF SKEYS
private static int numberOfKeys;
private final int keyNumber;
private SKEY() {
this.keyNumber = numberOfKeys;
keys[keyNumber] = this;
numberOfKeys++;
}
static int getNumberOfKeys() {
return SKEY.class.getFields().length;
}
int getKeyID() {
return keyNumber;
}
private Object readResolve() throws ObjectStreamException {
return keys[this.keyNumber];
}
@Override
public String toString() {
return Utils.findConstantFieldName(this);
}
static SKEY getKey(int keyNum) {
return keys[keyNum];
}
}
Methods:
MethodJavadoc
getKey
getKeyID
getNumberOfKeys/**
readResolve
jfreerails.world.top.TransactionAggregator
Javadoc:
/** * * Adds up the value of transactions. Implements GoF Template Method pattern. * Subclasses that aggregate a monetary sum should only override the method * <code>condition(int)</code>; subclasses that aggregate a non-monetary sum * should override all 4 protected methods. * * * @author Luke * */
Source code:
/**
*
* Adds up the value of transactions. Implements GoF Template Method pattern.
* Subclasses that aggregate a monetary sum should only override the method
* <code>condition(int)</code>; subclasses that aggregate a non-monetary sum
* should override all 4 protected methods.
*
*
* @author Luke
*
*/
public abstract class TransactionAggregator {
protected final ReadOnlyWorld w;
protected final FreerailsPrincipal principal;
protected Money[] monetaryTotals;
protected int runningTotal = 0;
private final GameTime[] DEFAULT_INTERVAL = new GameTime[] {
GameTime.BIG_BANG, GameTime.END_OF_THE_WORLD };
private GameTime[] timeValues = DEFAULT_INTERVAL;
public GameTime[] getTimes() {
// return defensive copy.
return timeValues.clone();
}
public void setTimes(GameTime[] times) {
if (1 > times.length) {
throw new IllegalArgumentException(
"There must be at least two values.");
}
timeValues = new GameTime[times.length];
timeValues[0] = times[0]; // since we start counting at 1.
for (int i = 1; i < times.length; i++) {
if (times[i].getTicks() < times[i - 1].getTicks()) {
throw new IllegalArgumentException("Time at index " + (i - 1)
+ " > time at index " + i + ".");
}
timeValues[i] = times[i];
}
}
public TransactionAggregator(ReadOnlyWorld w, FreerailsPrincipal principal) {
this.w = w;
this.principal = principal;
}
/** Returns the sum of the appropriate transactions. Do not override. */
final public Money calculateValue() {
Money[] values = calculateValues();
return values[0];
}
/**
* Returns the sum of the appropriate transactions up to (inclusive) each of
* the specified times. Do not override.
*/
final public Money[] calculateValues() {
setTotalsArrayLength(timeValues.length - 1);
int timeIndex = 0;
int numberOfTransactions = w.getNumberOfTransactions(this.principal);
setTotalsArrayLength(timeValues.length - 1);
for (int i = 0; i < numberOfTransactions; i++) {
GameTime time = w.getTransactionTimeStamp(principal, i);
int transactionTime = time.getTicks();
while (timeValues[timeIndex].getTicks() <= transactionTime) {
storeTotalIfAppropriate(timeIndex);
timeIndex++;
if (timeIndex >= timeValues.length) {
/*
* The current transaction occurred after the last of the
* specified times.
*/
return monetaryTotals;
}
}
if (timeIndex > 0 && condition(i)) {
incrementRunningTotal(i);
}
}
/*
* There are no more transactions and the last transaction occurred
* before one or more of the specified times.
*/
while (timeIndex < timeValues.length) {
storeTotalIfAppropriate(timeIndex);
timeIndex++;
}
return monetaryTotals;
}
private void storeTotalIfAppropriate(int timeIndex) {
if (timeIndex > 0) {
storeRunningTotal(timeIndex - 1);
}
}
/**
* Creates a new array with the specified length to store monetary totals
* and sets the running total to zero. Subclasses that aggregate other
* quantities should override this method and create the appropriate arrays.
*/
protected void setTotalsArrayLength(int length) {
monetaryTotals = new Money[length];
runningTotal = 0;
}
protected void incrementRunningTotal(int transactionID) {
Transaction t = w.getTransaction(principal, transactionID);
runningTotal += t.deltaCash().getAmount();
}
/**
* Stores the current running total in the totals array at the specified
* position.
*/
protected void storeRunningTotal(int timeIndex) {
monetaryTotals[timeIndex] = new Money(runningTotal);
}
/** Returns true if we should count the specified transactions. */
abstract protected boolean condition(int transactionID);
}
Methods:
MethodJavadoc
calculateValue/** Returns the sum of the appropriate transactions. Do not override. */
calculateValues/**
condition/** Returns true if we should count the specified transactions. */
getTimes
incrementRunningTotal
setTimes
setTotalsArrayLength/**
storeRunningTotal/**
storeTotalIfAppropriate
jfreerails.world.top.TypeID
Javadoc:
/** * This class stores an SKEY and an item index. * * @author Luke Lindsay */
Source code:
/**
* This class stores an SKEY and an item index.
*
* @author Luke Lindsay
*/
public class TypeID {
private final int id;
private final SKEY key;
public TypeID(int id, SKEY key) {
this.id = id;
this.key = key;
}
public SKEY getKey() {
return key;
}
public int getID() {
return id;
}
}
Methods:
MethodJavadoc
getID
getKey
jfreerails.world.top.WagonAndEngineTypesFactory
Javadoc:
/** * This class adds hard coded wagon and engine types to the World. Later the * wagon and engine types will be defined in an xml file, but this will do for * now. * * @author Luke * */
Source code:
/**
* This class adds hard coded wagon and engine types to the World. Later the
* wagon and engine types will be defined in an xml file, but this will do for
* now.
*
* @author Luke
*
*/
public class WagonAndEngineTypesFactory {
public void addTypesToWorld(World w) {
// Wagon types
WagonType[] wagonTypes = new WagonType[] {
new WagonType("Mail", WagonType.MAIL),
new WagonType("Passengers", WagonType.PASSENGER),
new WagonType("Livestock", WagonType.FAST_FREIGHT),
new WagonType("Coffee", WagonType.SLOW_FREIGHT),
new WagonType("Wood", WagonType.BULK_FREIGHT), };
for (int i = 0; i < wagonTypes.length; i++) {
w.add(SKEY.WAGON_TYPES, wagonTypes[i]);
}
// Engine types
EngineType[] engineTypes = new EngineType[] {
new EngineType("Grasshopper", 1000, new Money(10000), 10,
new Money(100)),
new EngineType("Norris", 1000, new Money(10000), 15, new Money(
100)), };
for (int i = 0; i < engineTypes.length; i++) {
w.add(SKEY.ENGINE_TYPES, engineTypes[i]);
}
}
}
Methods:
MethodJavadoc
addTypesToWorld
jfreerails.world.top.World
Javadoc:
/** * <p> * This class implements methods which can be used to alter the world. Notice * that in contrast to, say, <CODE>java.util.List</CODE> there is no remove() * method that shifts any subsequent elements to the left (subtracts one from * their indices). This means that an elements' position in a list can be used * as an address space independent way to reference the element. If you want to * remove an element from a list, you should set it to null, e.g. * </p> * <p> * <CODE>world.set(KEY.TRAINS, 5, null, player);</CODE> * </P> * <p> * Code that loops through lists should handle null values gracefully * </p> * * @author Luke * @author rob */
Source code:
/**
* <p>
* This class implements methods which can be used to alter the world. Notice
* that in contrast to, say, <CODE>java.util.List</CODE> there is no remove()
* method that shifts any subsequent elements to the left (subtracts one from
* their indices). This means that an elements' position in a list can be used
* as an address space independent way to reference the element. If you want to
* remove an element from a list, you should set it to null, e.g.
* </p>
* <p>
* <CODE>world.set(KEY.TRAINS, 5, null, player);</CODE>
* </P>
* <p>
* Code that loops through lists should handle null values gracefully
* </p>
*
* @author Luke
* @author rob
*/
public interface World extends ReadOnlyWorld {
int addActiveEntity(FreerailsPrincipal principal, Activity element);
void add(FreerailsPrincipal principal, int index, Activity element);
/**
* Appends the specified element to the end of the specified list and returns
* the index that can be used to retrieve it.
*/
int add(FreerailsPrincipal principal, KEY key, FreerailsSerializable element);
/**
* Appends the specified element to the end of the specified list and returns
* the index that can be used to retrieve it.
*
*/
int add(SKEY key, FreerailsSerializable element);
int addPlayer(Player player);
/**
* Adds the specified transaction to the specified principal's bank account.
*/
void addTransaction(FreerailsPrincipal p, Transaction t);
/**
* Returns a copy of this world object - making changes to this copy will
* not change this object.
*/
World defensiveCopy();
Activity removeLastActiveEntity(FreerailsPrincipal principal);
Activity removeLastActivity(FreerailsPrincipal principal, int index);
/**
* Removes the last element from the specified list.
*/
FreerailsSerializable removeLast(FreerailsPrincipal principal, KEY key);
/**
* Removes the last element from the specified list.
*
*/
FreerailsSerializable removeLast(SKEY key);
/**
* Removes and returns the last transaction added the the specified
* principal's bank account. This method is only here so that moves that add
* transactions can be undone.
*/
Transaction removeLastTransaction(FreerailsPrincipal p);
Player removeLastPlayer();
/**
* Replaces the element mapped to the specified item with the specified
* element.
*
*/
void set(ITEM item, FreerailsSerializable element);
/**
* Replaces the element at the specified position in the specified list with
* the specified element.
*/
void set(FreerailsPrincipal principal, KEY key, int index,
FreerailsSerializable element);
/**
* Replaces the element at the specified position in the specified list with
* the specified element.
*
*/
void set(SKEY key, int index, FreerailsSerializable element);
/**
* Replaces the tile at the specified position on the map with the specified
* tile.
*
*/
void setTile(int x, int y, FreerailsSerializable tile);
void setTime(GameTime t);
}
Methods:
MethodJavadoc
add
add/**
add/**
addActiveEntity
addPlayer
addTransaction/**
defensiveCopy/**
removeLast/**
removeLast/**
removeLastActiveEntity
removeLastActivity/**
removeLastPlayer
removeLastTransaction/**
set/**
set/**
set/**
setTile/**
setTime
jfreerails.world.top.WorldDiffs
Javadoc:
/** * An implementation of World that only stores differences relative to an * underlying world object. Below is some stylised code showing what this class * does. The <code>key</code> object could be a location on the map, a * position in a list etc. <code><pre> * HashMap underlyingWorldObject; * * HashMap differences; * * public void put(Object key, Object value) { * if (underlyingWorldObject.get(key).equals(value)) { * if (differences.containsKey(key)) { * differences.remove(key); * } * } else { * differences.put(key, value); * } * } * * public Object get(Object key) { * if (differences.containsKey(key)) { * return differences.get(key); * } else { * return underlyingWorldObject.get(key); * } * } * </code></pre> * * The advantages of using an instance of this class instead of a copy of the * world object are: * <ol> * <li> Uses less memory.</li> * <li> Lets you pinpoint where differences on the map are, so you don't need to * check every tile. </li> * </ol> * * * @author Luke * @version 2 * */
Source code:
/**
* An implementation of World that only stores differences relative to an
* underlying world object. Below is some stylised code showing what this class
* does. The <code>key</code> object could be a location on the map, a
* position in a list etc. <code><pre>
* HashMap underlyingWorldObject;
*
* HashMap differences;
*
* public void put(Object key, Object value) {
* if (underlyingWorldObject.get(key).equals(value)) {
* if (differences.containsKey(key)) {
* differences.remove(key);
* }
* } else {
* differences.put(key, value);
* }
* }
*
* public Object get(Object key) {
* if (differences.containsKey(key)) {
* return differences.get(key);
* } else {
* return underlyingWorldObject.get(key);
* }
* }
* </code></pre>
*
* The advantages of using an instance of this class instead of a copy of the
* world object are:
* <ol>
* <li> Uses less memory.</li>
* <li> Lets you pinpoint where differences on the map are, so you don't need to
* check every tile. </li>
* </ol>
*
*
* @author Luke
* @version 2
*
*/
public class WorldDiffs extends WorldImpl {
public enum LISTID {
ACTIVITY_LISTS, BANK_ACCOUNTS, CURRENT_BALANCE, ITEMS, LISTS, PLAYERS, SHARED_LISTS
}
private static final long serialVersionUID = -5993786533926919956L;
private final SortedMap<ListKey, Object> listDiff;
/** Stores the differences on the map, ImPoint are used as keys. */
private final HashMap<ImPoint, Object> mapDiff;
private final WorldImpl underlying;
public WorldDiffs(ReadOnlyWorld row){
listDiff = new TreeMap<ListKey, Object>();
mapDiff = new HashMap<ImPoint, Object>();
//Bit of a hack but it's not clear there is a better way, LL
underlying = (WorldImpl)row;
activityLists = new List3DDiff<ActivityAndTime>(listDiff,
underlying.activityLists, LISTID.ACTIVITY_LISTS);
bankAccounts = new List2DDiff<TransactionAndTimeStamp>(listDiff,
underlying.bankAccounts, LISTID.BANK_ACCOUNTS);
currentBalance = new List1DDiff<Money>(listDiff,
underlying.currentBalance, LISTID.CURRENT_BALANCE);
items = new List1DDiff<FreerailsSerializable>(listDiff,
underlying.items, LISTID.ITEMS);
lists = new List3DDiff<FreerailsSerializable>(listDiff,
underlying.lists, LISTID.LISTS);
players = new List1DDiff<Player>(listDiff, underlying.players,
LISTID.PLAYERS);
sharedLists = new List2DDiff<FreerailsSerializable>(listDiff,
underlying.sharedLists, LISTID.SHARED_LISTS);
time = underlying.time;
}
/**
* The iterator returns instances of java.awt.Point that store the
* coordinates of tiles that are different to the underlying world object.
*/
public Iterator<ImPoint> getMapDiffs() {
return mapDiff.keySet().iterator();
}
public Iterator<ListKey> getListDiffs() {
return listDiff.keySet().iterator();
}
public Object getDiff(ListKey key){
return listDiff.get(key);
}
@Override
public int getMapHeight() {
return underlying.getMapHeight();
}
@Override
public int getMapWidth() {
return underlying.getMapWidth();
}
@Override
public FreerailsSerializable getTile(int x, int y) {
ImPoint p = new ImPoint(x, y);
if (this.mapDiff.containsKey(p)) {
return (FreerailsSerializable) this.mapDiff.get(p);
}
return underlying.getTile(x, y);
}
/** Used by unit tests. */
public int numberOfMapDifferences() {
return this.mapDiff.size();
}
/** Used by unit tests. */
public int listDiffs() {
return listDiff.size();
}
/**
* After this method returns, all differences are cleared and calls to
* methods on this object should produce the same results as calls the the
* corresponding methods on the underlying world object.
*/
public void reset() {
time = underlying.currentTime();
mapDiff.clear();
listDiff.clear();
}
@Override
public void setTile(int x, int y, FreerailsSerializable tile) {
ImPoint p = new ImPoint(x, y);
if (Utils.equal(underlying.getTile(x, y), tile)) {
if (this.mapDiff.containsKey(p)) {
this.mapDiff.remove(p);
return;
}
} else {
this.mapDiff.put(p, tile);
}
}
public boolean isDifferent(){
return (mapDiff.size() != 0) || (listDiff.size() != 0);
}
public ReadOnlyWorld getUnderlying() {
return underlying;
}
}
Methods:
MethodJavadoc
getDiff
getListDiffs
getMapDiffs/**
getMapHeight
getMapWidth
getTile
getUnderlying
isDifferent
listDiffs/** Used by unit tests. */
numberOfMapDifferences/** Used by unit tests. */
reset/**
setTile
jfreerails.world.top.WorldImpl
Javadoc:
/** * An implementation of World that uses standard java.util collections * internally. * * @author Luke * */
Source code:
/**
* An implementation of World that uses standard java.util collections
* internally.
*
* @author Luke
*
*/
public class WorldImpl implements World {
public class ActivityIteratorImpl implements ActivityIterator {
public int activityIndex = 0;
private ActivityAndTime ant;
private List<ActivityAndTime> currentList;
public int size;
public ActivityIteratorImpl(int playerIndex, int index) {
currentList = activityLists.get(playerIndex, index);
size = currentList.size();
ant = currentList.get(activityIndex);
}
public double absolute2relativeTime(double t) {
double dt = t - ant.startTime;
dt = Math.min(dt, ant.act.duration());
return dt;
}
public Activity getActivity() {
return ant.act;
}
public double getDuration() {
return ant.act.duration();
}
public double getFinishTime() {
double ticks = ant.startTime + ant.act.duration();
return ticks;
}
public double getStartTime() {
return ant.startTime;
}
public FreerailsSerializable getState(double t) {
double dt = absolute2relativeTime(t);
return ant.act.getState(dt);
}
public boolean hasNext() {
return (activityIndex + 1) < size;
}
public void nextActivity() {
if (!hasNext()) {
throw new NoSuchElementException();
}
activityIndex++;
ant = currentList.get(activityIndex);
}
public void gotoLastActivity() {
activityIndex = size - 1;
ant = currentList.get(activityIndex);
}
public boolean hasPrevious() {
return activityIndex >= 1;
}
public void previousActivity() throws NoSuchElementException {
if (!hasPrevious()) {
throw new NoSuchElementException();
}
activityIndex--;
ant = currentList.get(activityIndex);
}
}
public static class ActivityAndTime implements FreerailsSerializable {
private static final long serialVersionUID = -5149207279086814649L;
public final Activity act;
public final double startTime;
ActivityAndTime(Activity act, double time) {
this.act = act;
startTime = time;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ActivityAndTime))
return false;
final ActivityAndTime activityAndTime = (ActivityAndTime) o;
if (!act.equals(activityAndTime.act))
return false;
if (startTime != activityAndTime.startTime)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = act.hashCode();
result = 29 * result + (int) startTime;
return result;
}
}
private static final long serialVersionUID = 3544393612684505393L;
/** A 3D list: D1 is player, D2 is train id, D3 is train position. */
List3D<ActivityAndTime> activityLists;
/** A 2D list: D1 is player, D2 is transaction. */
List2D<TransactionAndTimeStamp> bankAccounts;
List1D<Money> currentBalance;
List1D<FreerailsSerializable> items;
/** A 3D list: D1 is player, D2 is type, D3 is element. */
List3D<FreerailsSerializable> lists;
FreerailsSerializable[][] map;
List1D<Player> players;
/** A 2D list: D1 is type, D2 is element. */
List2D<FreerailsSerializable> sharedLists;
GameTime time = GameTime.BIG_BANG;
public WorldImpl() {
this(0, 0);
}
public WorldImpl(int mapWidth, int mapHeight) {
activityLists = new List3DImpl<ActivityAndTime>(0, 0);
bankAccounts = new List2DImpl<TransactionAndTimeStamp>(0);
currentBalance = new List1DImpl<Money>();
items = new List1DImpl<FreerailsSerializable>(ITEM.getNumberOfKeys());
lists = new List3DImpl<FreerailsSerializable>(0, KEY.getNumberOfKeys());
players = new List1DImpl<Player>();
sharedLists = new List2DImpl<FreerailsSerializable>(SKEY
.getNumberOfKeys());
time = GameTime.BIG_BANG;
setupItems();
setupMap(mapWidth, mapHeight);
}
@SuppressWarnings("unchecked")
public void add(FreerailsPrincipal p, int index, Activity element) {
int playerIndex = p.getWorldIndex();
int lastID = activityLists.sizeD3(playerIndex, index) - 1;
ActivityAndTime last = activityLists.get(playerIndex, index, lastID);
double duration = last.act.duration();
double lastFinishTime = last.startTime + duration;
double thisStartTime = Math.max(lastFinishTime, currentTime()
.getTicks());
ActivityAndTime ant = new ActivityAndTime(element, thisStartTime);
activityLists.addD3(playerIndex, index, ant);
}
public int add(FreerailsPrincipal p, KEY key, FreerailsSerializable element) {
int playerIndex = p.getWorldIndex();
return lists.addD3(playerIndex, key.getKeyID(), element);
}
public int add(SKEY key, FreerailsSerializable element) {
return sharedLists.addD2(key.getKeyID(), element);
}
public int addActiveEntity(FreerailsPrincipal p, Activity element) {
int playerIndex = p.getWorldIndex();
int index = activityLists.addD2(playerIndex);
ActivityAndTime ant = new ActivityAndTime(element, currentTime()
.getTicks());
activityLists.addD3(playerIndex, index, ant);
return index;
}
/**
* @param player
* Player to add
* @return index of the player
*/
public int addPlayer(Player player) {
if (null == player) {
throw new NullPointerException();
}
int index = players.add(player);
bankAccounts.addD1();
currentBalance.add(new Money(0));
lists.addD1();
for (int i = 0; i < KEY.getNumberOfKeys(); i++) {
lists.addD2(index);
}
activityLists.addD1();
return index;
}
public void addTransaction(FreerailsPrincipal p, Transaction t) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = new TransactionAndTimeStamp(t, time);
bankAccounts.addD2(playerIndex, tats);
Money oldBalance = currentBalance.get(playerIndex);
Money newBalance = new Money(t.deltaCash().getAmount()
+ oldBalance.getAmount());
currentBalance.set(playerIndex, newBalance);
}
public boolean boundsContain(FreerailsPrincipal p, KEY k, int index) {
if (!isPlayer(p)) {
return false;
} else if (index >= 0 && index < this.size(p, k)) {
return true;
} else {
return false;
}
}
public boolean boundsContain(int x, int y) {
if (x >= 0 && x < getMapWidth() && y >= 0 && y < getMapHeight()) {
return true;
}
return false;
}
public boolean boundsContain(SKEY k, int index) {
return (index >= 0 && index < this.size(k));
}
public GameTime currentTime() {
return time;
}
public World defensiveCopy() {
return (World) Utils.cloneBySerialisation(this);
}
@Override
public boolean equals(Object o) {
if (o instanceof WorldImpl) {
WorldImpl test = (WorldImpl) o;
// Compare players
int numberOfPlayers = getNumberOfPlayers();
if (numberOfPlayers != test.getNumberOfPlayers())
return false;
for (int i = 0; i < numberOfPlayers; i++) {
if (!getPlayer(i).equals(test.getPlayer(i)))
return false;
}
// Compare lists
if (!lists.equals(test.lists)) {
return false;
}
if (!sharedLists.equals(test.sharedLists)) {
return false;
}
if (!activityLists.equals(test.activityLists)) {
return false;
}
if (!items.equals(test.items)) {
return false;
}
if (!bankAccounts.equals(test.bankAccounts)) {
return false;
}
// Compare maps
if ((this.getMapWidth() != test.getMapWidth())
|| (this.getMapHeight() != test.getMapHeight())) {
return false;
}
for (int x = 0; x < this.getMapWidth(); x++) {
for (int y = 0; y < this.getMapHeight(); y++) {
if (!getTile(x, y).equals(test.getTile(x, y))) {
return false;
}
}
}
// phew!
return true;
}
return false;
}
public FreerailsSerializable get(FreerailsPrincipal p, KEY key, int index) {
int playerIndex = p.getWorldIndex();
return lists.get(playerIndex, key.getKeyID(), index);
}
public FreerailsSerializable get(ITEM item) {
return items.get(item.getKeyID());
}
public FreerailsSerializable get(SKEY key, int index) {
return sharedLists.get(key.getKeyID(), index);
}
public ActivityIterator getActivities(final FreerailsPrincipal p, int index) {
final int playerIndex = p.getWorldIndex();
return new ActivityIteratorImpl(playerIndex, index);
}
public Money getCurrentBalance(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
return currentBalance.get(playerIndex);
}
public int getID(FreerailsPrincipal p) {
return p.getWorldIndex();
}
public int getMapHeight() {
if (map.length == 0) {
// When the map size is 0*0 we get a
// java.lang.ArrayIndexOutOfBoundsException: 0
// if we don't have the check above.
return 0;
}
return map[0].length;
}
public int getMapWidth() {
return map.length;
}
public int getNumberOfPlayers() {
return players.size();
}
public int getNumberOfTransactions(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
return bankAccounts.sizeD2(playerIndex);
}
public Player getPlayer(int i) {
return players.get(i);
}
public FreerailsSerializable getTile(int x, int y) {
return map[x][y];
}
public Transaction getTransaction(FreerailsPrincipal p, int i) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = bankAccounts.get(playerIndex, i);
return tats.getT();
}
public GameTime getTransactionTimeStamp(FreerailsPrincipal p, int i) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = bankAccounts.get(playerIndex, i);
return tats.getTimeStamp();
}
public Pair<Transaction, GameTime> getTransactionAndTimeStamp(
FreerailsPrincipal p, int i) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = bankAccounts.get(playerIndex, i);
return new Pair<Transaction, GameTime>(tats.getT(), tats.getTimeStamp());
}
@Override
public int hashCode() {
int result;
result = players.size();
return result;
}
public boolean isPlayer(FreerailsPrincipal p) {
if (p.getWorldIndex() >= 0 && p.getWorldIndex() < players.size()) {
return true;
} else {
return false;
}
}
public FreerailsSerializable removeLast(FreerailsPrincipal p, KEY key) {
int playerIndex = p.getWorldIndex();
return lists.removeLastD3(playerIndex, key.getKeyID());
}
public FreerailsSerializable removeLast(SKEY key) {
return sharedLists.removeLastD2(key.getKeyID());
}
public Activity removeLastActiveEntity(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
int lastID = activityLists.sizeD2(playerIndex) - 1;
Activity act = activityLists.removeLastD3(playerIndex, lastID).act;
activityLists.removeLastD2(playerIndex);
return act;
}
public Activity removeLastActivity(FreerailsPrincipal p, int index) {
int playerIndex = p.getWorldIndex();
if (activityLists.sizeD3(playerIndex, index) < 2)
throw new IllegalStateException();
Activity act = activityLists.removeLastD3(playerIndex, index).act;
return act;
}
/**
* Removes the last player to be added.
*
* @return the player that was removed.
* @throws IllegalStateException
* if any elements belonging to the player have not been
* removed.
*/
public Player removeLastPlayer() {
int playerID = bankAccounts.removeLastD1();
while (lists.sizeD2(playerID) > 0)
lists.removeLastD2(playerID);
lists.removeLastD1();
currentBalance.removeLast();
activityLists.removeLastD1();
return players.removeLast();
}
public Transaction removeLastTransaction(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = bankAccounts.removeLastD2(playerIndex);
Money oldBalance = currentBalance.get(playerIndex);
Money newBalance = new Money(oldBalance.getAmount()
- tats.getT().deltaCash().getAmount());
currentBalance.set(playerIndex, newBalance);
return tats.getT();
}
public void set(FreerailsPrincipal p, KEY key, int index,
FreerailsSerializable element) {
int playerIndex = p.getWorldIndex();
lists.set(playerIndex, key.getKeyID(), index, element);
}
public void set(ITEM item, FreerailsSerializable element) {
items.set(item.getKeyID(), element);
}
public void set(SKEY key, int index, FreerailsSerializable element) {
sharedLists.set(key.getKeyID(), index, element);
}
public void setTile(int x, int y, FreerailsSerializable element) {
map[x][y] = element;
}
public void setTime(GameTime t) {
time = t;
}
void setupItems() {
this.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
time = new GameTime(0);
this.set(ITEM.ECONOMIC_CLIMATE, EconomicClimate.MODERATION);
}
public void setupMap(int mapWidth, int mapHeight) {
map = new FreerailsSerializable[mapWidth][mapHeight];
for (int x = 0; x < mapWidth; x++) {
for (int y = 0; y < mapHeight; y++) {
map[x][y] = FreerailsTile.NULL;
}
}
}
public int size(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
return activityLists.sizeD2(playerIndex);
}
public int size(FreerailsPrincipal p, KEY key) {
int playerIndex = p.getWorldIndex();
return lists.sizeD3(playerIndex, key.getKeyID());
}
public int size(SKEY key) {
return sharedLists.sizeD2(key.getKeyID());
}
public int getNumberOfActiveEntities(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
return activityLists.sizeD2(playerIndex);
}
}
Methods:
MethodJavadoc
add
add
add
addActiveEntity
addPlayer/**
addTransaction
boundsContain
boundsContain
boundsContain
currentTime
defensiveCopy
get
get
get
getActivities
getCurrentBalance
getID
getMapHeight
getMapWidth
getNumberOfActiveEntities
getNumberOfPlayers
getNumberOfTransactions
getPlayer
getTile
getTransaction
getTransactionAndTimeStamp
getTransactionTimeStamp
isPlayer
removeLast/**
removeLast
removeLastActiveEntity
removeLastActivity
removeLastPlayer/**
removeLastTransaction
set
set
set
setTile
setTime/**
setupItems
setupMap
size
size
size
jfreerails.world.top.WorldIterator
Javadoc:
/** * This interface lets the caller access the results of a search in the * gameworld. It is similar in concept to <code>java.sql.ResultSet</code>. * * @author Luke * */
Source code:
/**
* This interface lets the caller access the results of a search in the
* gameworld. It is similar in concept to <code>java.sql.ResultSet</code>.
*
* @author Luke
*
*/
public interface WorldIterator {
public static final int BEFORE_FIRST = -1;
/**
* Moves the cursor down one row from its current position.
*/
boolean next();
/**
* Moves the cursor up one row from its current position.
*/
boolean previous();
/**
* Moves the cursor to before the first element and updates any cached
* values.
*/
void reset();
/** Returns the element the cursor is pointing to. */
FreerailsSerializable getElement();
/**
* Returns the index of the element the cursor is pointing to. The value
* returned is index you would need to use in
* <code>World.get(KEY key, int index)</code> to retrieve the same element
* as is returned by <code>getElement()</code>
*/
int getIndex();
/**
* Returns the number of the row where the cursor is (the first row is 0).
*/
int getRowID();
/** Returns the number of rows. */
int size();
/**
* Moves the cursor to the specified index.
*
* @throws NoSuchElementException
* if index out of range
*/
void gotoIndex(int i);
/** Moves the cursor to the specified index. */
void gotoRow(int row);
/**
* Returns the number of the row where the cursor is (the first row is 1).
*/
int getNaturalNumber();
}
Methods:
MethodJavadoc
getElement/** Returns the element the cursor is pointing to. */
getIndex/**
getNaturalNumber/**
getRowID/**
gotoIndex/**
gotoRow/** Moves the cursor to the specified index. */
next/**
previous/**
reset/**
size/** Returns the number of rows. */
jfreerails.world.top.WorldListListener
Javadoc:
/** * Classes that need to be notified of changes to the lists on the world object * should implement this interface. * * @author Luke Lindsay * */
Source code:
/**
* Classes that need to be notified of changes to the lists on the world object
* should implement this interface.
*
* @author Luke Lindsay
*
*/
public interface WorldListListener {
void listUpdated(KEY key, int index, FreerailsPrincipal principal);
void itemAdded(KEY key, int index, FreerailsPrincipal principal);
void itemRemoved(KEY key, int index, FreerailsPrincipal principal);
}
Methods:
MethodJavadoc
itemAdded
itemRemoved
listUpdated
jfreerails.world.top.WorldMapListener
Javadoc:
/** * Classes that need to be notified of changes to the map on the world object * should implement this interface. * * @author Luke Lindsay * * */
Source code:
/**
* Classes that need to be notified of changes to the map on the world object
* should implement this interface.
*
* @author Luke Lindsay
*
*
*/
public interface WorldMapListener {
/**
* Called when tiles have changed.
*
* @param tilesChanged
* rectangle containing the tiles that have change; all the
* points contained by the rectangle must be within the map's
* bounds.
*/
void tilesChanged(Rectangle tilesChanged);
}
Methods:
MethodJavadoc
tilesChanged/**
jfreerails.world.track.EightRotationsOfTrackPieceProducer
Javadoc:
/** * This class provides a method to get the eight rotations of a track template. * E.g. if the template is: 010 010 110 it returns: 010 001 100 010 110 111 110 * 100 000 etc. * * * @author Luke Lindsay * @version 1.0 */
Source code:
/**
* This class provides a method to get the eight rotations of a track template.
* E.g. if the template is: 010 010 110 it returns: 010 001 100 010 110 111 110
* 100 000 etc.
*
*
* @author Luke Lindsay
* @version 1.0
*/
public class EightRotationsOfTrackPieceProducer {
/**
* The method that returns the rotations.
*
* @param trackBlueprint
* A 9bit value that serves as the template.
* @return An array of 8 9-bit values that have been generated by rotating
* the template.
*/
public static int[] getRotations(int trackBlueprint) {
int trackTemplate = trackBlueprint;
int[] derivedTrackPieces = new int[8];
for (int i = 0; i < 8; i++) {
derivedTrackPieces[i] = trackTemplate;
boolean[][] trackTemplateBooleanArray = getTrackBooleanArray(trackTemplate);
trackTemplateBooleanArray = rotateTrackNodeClockwise(trackTemplateBooleanArray);
trackTemplate = getTrackGraphicID(trackTemplateBooleanArray);
}
return derivedTrackPieces;
}
private static boolean[][] getTrackBooleanArray(int trackGraphicInt) {
boolean[][] trackBooleanArray = new boolean[3][3];
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
if (((trackGraphicInt >> (3 * y + x)) & 1) == 1) {
trackBooleanArray[x][y] = true;
}
}
}
return trackBooleanArray;
}
private static int getTrackGraphicID(boolean[][] railsList) {
int trackGraphicNumber = 0;
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
if (railsList[x][y]) {
trackGraphicNumber = trackGraphicNumber
| (1 << (3 * y + x));
}
}
}
return trackGraphicNumber;
}
private static boolean[][] rotateTrackNodeClockwise(boolean[][] source) {
Point[][] grabValueFrom = new Point[3][];
grabValueFrom[0] = new Point[] { new Point(0, 1), new Point(0, 0),
new Point(1, 0) };
grabValueFrom[1] = new Point[] { new Point(0, 2), new Point(1, 1),
new Point(2, 0) };
grabValueFrom[2] = new Point[] { new Point(1, 2), new Point(2, 2),
new Point(2, 1) };
/*
* I think there is a neater way of doing this, let me know if you know
* it! Luke
*/
boolean[][] output = new boolean[3][3];
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
Point point = grabValueFrom[y][x];
/*
* y,x because of the way I defined grabValueFrom[][] above.
*/
output[x][y] = source[point.x][point.y];
}
}
return output;
}
}
Methods:
MethodJavadoc
getRotations/**
getTrackBooleanArray
getTrackGraphicID
rotateTrackNodeClockwise
jfreerails.world.track.FreerailsTile
Javadoc:
/** * A tile on the map. * * Instances are stored in a HashMap to avoid creating 100,000s of objects. * * @author Luke */
Source code:
/**
* A tile on the map.
*
* Instances are stored in a HashMap to avoid creating 100,000s of objects.
*
* @author Luke
*/
public class FreerailsTile implements TerrainTile,
FreerailsSerializable {
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final FreerailsTile that = (FreerailsTile) o;
if (terrainType != that.terrainType)
return false;
if (trackPiece != null ? !trackPiece.equals(that.trackPiece)
: that.trackPiece != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = (trackPiece != null ? trackPiece.hashCode() : 0);
result = 29 * result + terrainType;
return result;
}
private static final long serialVersionUID = 3617574907538847544L;
public static final FreerailsTile NULL = new FreerailsTile(0);
private final TrackPiece trackPiece;
private final int terrainType;
private static HashMap<FreerailsTile, FreerailsTile> instances = new HashMap<FreerailsTile, FreerailsTile>();
public static FreerailsTile getInstance(int terrainType) {
FreerailsTile tile = new FreerailsTile(terrainType);
if (instances.containsKey(tile)) {
return instances.get(tile);
}
instances.put(tile, tile);
return tile;
}
public static FreerailsTile getInstance(int terrainType,
TrackPiece trackPiece) {
FreerailsTile tile = new FreerailsTile(terrainType, trackPiece);
if (instances.containsKey(tile)) {
return instances.get(tile);
}
instances.put(tile, tile);
return tile;
}
private Object readResolve() throws ObjectStreamException {
if (instances.containsKey(this)) {
return instances.get(this);
}
instances.put(this, this);
return this;
}
private FreerailsTile(int terrainType) {
this.terrainType = terrainType;
this.trackPiece = NullTrackPiece.getInstance();
}
private FreerailsTile(int terrainType, TrackPiece trackPiece) {
this.terrainType = terrainType;
this.trackPiece = trackPiece;
}
public int getTerrainTypeID() {
return terrainType;
}
@Override
public String toString() {
return "trackPiece=" + trackPiece.toString() + " and terrainType is "
+ terrainType;
}
public TrackPiece getTrackPiece() {
return trackPiece;
}
public boolean hasTrack(){
return trackPiece.getTrackTypeID() != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER;
}
}
Methods:
MethodJavadoc
getInstance
getInstance
getTerrainTypeID/**
getTrackPiece
hasTrack
readResolve
jfreerails.world.track.LegalTrackConfigurations
Javadoc:
/** * Stores the legal track configurations for a type of track. * * @author Luke. */
Source code:
/**
* Stores the legal track configurations for a type of track.
*
* @author Luke.
*/
final public class LegalTrackConfigurations implements FreerailsSerializable {
private static final long serialVersionUID = 3617295631735928119L;
private final ImHashSet<TrackConfiguration> legalConfigs;// = new
// HashSet<TrackConfiguration>();
private final int maximumConsecutivePieces;
public LegalTrackConfigurations(int max,
ArrayList<String> legalTrackTemplatesArrayList) {
maximumConsecutivePieces = max;
HashSet<TrackConfiguration> temp = new HashSet<TrackConfiguration>();
// Iterate over the track templates.
for (int i = 0; i < legalTrackTemplatesArrayList.size(); i++) {
String trackTemplateString = legalTrackTemplatesArrayList.get(i);
processTemplate(trackTemplateString, temp);
}
legalConfigs = new ImHashSet<TrackConfiguration>(temp);
}
public LegalTrackConfigurations(int max, String[] legalTrackTemplatesArray) {
maximumConsecutivePieces = max;
HashSet<TrackConfiguration> temp = new HashSet<TrackConfiguration>();
for (int i = 0; i < legalTrackTemplatesArray.length; i++) {
processTemplate(legalTrackTemplatesArray[i], temp);
}
legalConfigs = new ImHashSet<TrackConfiguration>(temp);
}
@Override
public boolean equals(Object o) {
if (o instanceof LegalTrackConfigurations) {
LegalTrackConfigurations test = (LegalTrackConfigurations) o;
if (this.maximumConsecutivePieces == test
.getMaximumConsecutivePieces()
&& this.legalConfigs.equals(test.legalConfigs)) {
return true;
}
return false;
}
return false;
}
public Iterator<TrackConfiguration> getLegalConfigurationsIterator() {
return legalConfigs.iterator();
}
public int getMaximumConsecutivePieces() {
return maximumConsecutivePieces;
}
@Override
public int hashCode() {
int result;
result = maximumConsecutivePieces;
result = 29 * result
+ (legalConfigs != null ? legalConfigs.hashCode() : 0);
return result;
}
static private void processTemplate(String trackTemplateString,
HashSet<TrackConfiguration> temp) {
int trackTemplate = Integer.parseInt(trackTemplateString, 2);
// Check for invalid parameters.
if ((trackTemplate > 511) || (trackTemplate < 0)) {
throw new IllegalArgumentException("trackTemplate = "
+ trackTemplate + ", it should be in the range 0-511");
}
int[] rotationsOfTrackTemplate = EightRotationsOfTrackPieceProducer
.getRotations(trackTemplate);
for (int k = 0; k < rotationsOfTrackTemplate.length; k++) {
int i = rotationsOfTrackTemplate[k];
TrackConfiguration trackConfiguration = TrackConfiguration
.from9bitTemplate(i);
if (!temp.contains(trackConfiguration)) {
temp.add(trackConfiguration);
}
}
}
public boolean trackConfigurationIsLegal(
TrackConfiguration trackConfiguration) {
return legalConfigs.contains(trackConfiguration);
}
}
Methods:
MethodJavadoc
getLegalConfigurationsIterator
getMaximumConsecutivePieces
processTemplate
trackConfigurationIsLegal
jfreerails.world.track.LegalTrackPlacement
Javadoc:
/** * This class encapsulates the rules governing where, that is, on what terrain, * track of a given type can be built. * * @author lindsal */
Source code:
/**
* This class encapsulates the rules governing where, that is, on what terrain,
* track of a given type can be built.
*
* @author lindsal
*/
public final class LegalTrackPlacement implements FreerailsSerializable {
private static final long serialVersionUID = 3616445687756437049L;
private final ImHashSet<TerrainType.Category> terrainTypes;// = new
// HashSet<TerrainType.Category>();
public enum PlacementRule {
ONLY_ON_THESE, ANYWHERE_EXCEPT_ON_THESE
}
private final PlacementRule placementRule;
@Override
public int hashCode() {
return (placementRule != null ? placementRule.hashCode() : 0);
}
public LegalTrackPlacement(HashSet<TerrainType.Category> types,
PlacementRule placementRule) {
this.placementRule = placementRule;
Iterator<TerrainType.Category> iterator = types.iterator();
HashSet<TerrainType.Category> temp = new HashSet<TerrainType.Category>();
while (iterator.hasNext()) {
temp.add(iterator.next());
}
terrainTypes = new ImHashSet<TerrainType.Category>(temp);
}
public boolean canBuildOnThisTerrain(TerrainType.Category terrainType) {
if (PlacementRule.ONLY_ON_THESE == placementRule) {
return terrainTypes.contains(terrainType);
}
return !terrainTypes.contains(terrainType);
}
@Override
public boolean equals(Object o) {
if (o instanceof LegalTrackPlacement) {
LegalTrackPlacement test = (LegalTrackPlacement) o;
if (this.placementRule.equals(test.getPlacementRule())
&& this.terrainTypes.equals(test.terrainTypes)) {
return true;
}
return false;
}
return false;
}
public PlacementRule getPlacementRule() {
return placementRule;
}
}
Methods:
MethodJavadoc
canBuildOnThisTerrain
getPlacementRule
jfreerails.world.track.NullTrackPiece
Javadoc:
/** * A track piece that doesn't exist - using this avoids needing to check against * null before calling the methods on a track piece. * * @author lindsal */
Source code:
/**
* A track piece that doesn't exist - using this avoids needing to check against
* null before calling the methods on a track piece.
*
* @author lindsal
*/
final public class NullTrackPiece implements TrackPiece {
private static final long serialVersionUID = 3258413915376268599L;
private static final TrackPiece nullTrackPiece = new NullTrackPiece();
private static final int NO_OWNER = Integer.MIN_VALUE;
private NullTrackPiece() {
}
public static TrackPiece getInstance() {
return nullTrackPiece;
}
public int getTrackGraphicID() {
return 0;
}
public TrackRule getTrackRule() {
return NullTrackType.getInstance();
}
public TrackConfiguration getTrackConfiguration() {
return TrackConfiguration.from9bitTemplate(0);
}
private Object readResolve() throws ObjectStreamException {
return nullTrackPiece;
}
@Override
public boolean equals(Object o) {
return o == this;
}
@Override
public int hashCode() {
return 777;
}
public int getOwnerID() {
return NO_OWNER;
}
public int getTrackTypeID() {
return NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER;
}
}
Methods:
MethodJavadoc
getInstance
getOwnerID
getTrackConfiguration
getTrackGraphicID
getTrackRule
getTrackTypeID
readResolve
jfreerails.world.track.NullTrackType
Javadoc:
/** * The type of a Null track piece. TODO maybe it would be simpler to get rid of * this and just check against null! * * @author lindsal */
Source code:
/**
* The type of a Null track piece. TODO maybe it would be simpler to get rid of
* this and just check against null!
*
* @author lindsal
*/
final public class NullTrackType implements TrackRule {
private static final long serialVersionUID = 3257849891614306614L;
public static final int NULL_TRACK_TYPE_RULE_NUMBER = -999;
private static final NullTrackType nullTrackType = new NullTrackType();
private NullTrackType() {
}
private Object readResolve() throws ObjectStreamException {
return nullTrackType;
}
public static NullTrackType getInstance() {
return nullTrackType;
}
public boolean canBuildOnThisTerrainType(TerrainType.Category TerrainType) {
return true; // No track is possible anywhere.
}
public Step[] getLegalRoutes(
jfreerails.world.common.Step directionComingFrom) {
return new Step[0];
}
public int getMaximumConsecutivePieces() {
return -1;
}
public String getTypeName() {
return "NullTrackType";
}
public boolean testTrackPieceLegality(int trackTemplateToTest) {
if (trackTemplateToTest != 0) {
return false;
}
return true;
}
public boolean trackPieceIsLegal(TrackConfiguration config) {
return testTrackPieceLegality(config.getTrackGraphicsID());
}
public Iterator<TrackConfiguration> getLegalConfigurationsIterator() {
throw new UnsupportedOperationException("Method not implemented yet!");
}
public TrackPiece getTrackPiece(TrackConfiguration config, int owner) {
throw new UnsupportedOperationException("Method not implemented yet!");
}
public boolean isStation() {
return false;
}
@Override
public boolean equals(Object o) {
return o == this;
}
@Override
public int hashCode() {
return 666;
}
public int getStationRadius() {
return 0;
}
public Money getPrice() {
return new Money(0);
}
public Money getMaintenanceCost() {
return new Money(0);
}
public TrackCategories getCategory() {
return TrackCategories.non;
}
public int compareTo(TrackRule arg0) {
// TODO Auto-generated method stub
return 0;
}
public boolean isDouble() {
return false;
}
public Money getFixedCost() {
return Money.ZERO;
}
}
Methods:
MethodJavadoc
canBuildOnThisTerrainType
compareTo
getCategory
getFixedCost
getInstance
getLegalConfigurationsIterator
getLegalRoutes
getMaintenanceCost
getMaximumConsecutivePieces
getPrice
getStationRadius
getTrackPiece
getTypeName
isDouble
isStation
readResolve
testTrackPieceLegality
trackPieceIsLegal
jfreerails.world.track.TrackConfiguration
Javadoc:
/** * An instance of this class represents one of the possible track configurations * in a map square - the combinations of directions in which track can be laid. * Instances of this class cannot be created and must be obtained via the static * methods herein. * * @author Luke */
Source code:
/**
* An instance of this class represents one of the possible track configurations
* in a map square - the combinations of directions in which track can be laid.
* Instances of this class cannot be created and must be obtained via the static
* methods herein.
*
* @author Luke
*/
final public class TrackConfiguration implements FlatTrackTemplate {
private static final long serialVersionUID = 3618695301330974512L;
private static final ArrayList<TrackConfiguration> flatTrackConfigurations = setupConfigurations();
public static final int LENGTH_OF_STRAIGHT_TRACK_PIECE = 200;
/**
* @return the superposition of two track templates
*/
public static TrackConfiguration add(FlatTrackTemplate c,
FlatTrackTemplate v) {
/*
* int x=v.getX()+1; int y=v.getY()+1; int oldTemplate
* =c.getTrackGraphicsNumber(); int newTemplate = oldTemplate | (1 <<
* (3 * y + x));
*/
int newTemplate = c.get9bitTemplate() | v.get9bitTemplate();
return from9bitTemplate(newTemplate);
}
public static TrackConfiguration from9bitTemplate(int i) {
return flatTrackConfigurations.get(i);
}
public static TrackConfiguration getFlatInstance(Step v) {
return from9bitTemplate(v.get9bitTemplate());
}
public static TrackConfiguration getFlatInstance(String trackTemplate) {
int i = TrackConfiguration.stringTemplate2Int(trackTemplate);
return (flatTrackConfigurations.get(i));
}
private static ArrayList<TrackConfiguration> setupConfigurations() {
ArrayList<TrackConfiguration> configurations = new ArrayList<TrackConfiguration>(
512);
for (int i = 0; i < 512; i++) {
configurations.add(i, new TrackConfiguration(i));
}
return configurations;
}
public static int stringTemplate2Int(String templateString) {
// Hack - so that result is as expected by earlier written code.
StringBuffer strb = new StringBuffer(templateString);
strb = strb.reverse();
templateString = strb.toString();
// End of hack
return Integer.parseInt(templateString, 2);
}
/**
* @return the TrackConfiguration representing the track section c minus the
* track sections represented by v.
*/
public static TrackConfiguration subtract(FlatTrackTemplate c,
FlatTrackTemplate v) {
/*
* int x=v.getX()+1; int y=v.getY()+1; int oldTemplate
* =c.getTrackGraphicsNumber(); int newTemplate = oldTemplate ^ (1 <<
* (3 * y + x));
*/
int newTemplate = c.get9bitTemplate() & (~v.get9bitTemplate());
return from9bitTemplate(newTemplate);
}
private final int length;
private final int configuration;
private TrackConfiguration(int configuration) {
this.configuration = configuration;
// Calculate length.
int tempLength = 0;
Step[] vectors = Step.getList();
for (int i = 0; i < vectors.length; i++) {
if (this.contains(vectors[i].get9bitTemplate())) {
tempLength += vectors[i].getLength();
}
}
length = tempLength;
}
public boolean contains(FlatTrackTemplate ftt) {
int trackTemplate = ftt.get9bitTemplate();
return contains(trackTemplate);
}
public boolean contains(int trackTemplate) {
if ((trackTemplate | this.configuration) == this.configuration) {
return true;
}
return false;
}
public int get8bitTemplate() {
int newTemplate = 0;
Step[] vectors = Step.getList();
for (int i = 0; i < vectors.length; i++) {
if (this.contains(vectors[i])) {
newTemplate = newTemplate | vectors[i].get8bitTemplate();
}
}
return newTemplate;
}
/**
* @return an int representing this track configuration.
*/
public int get9bitTemplate() {
return configuration;
}
/**
* Returns the length of track used in this configuration. Used to calculate
* the cost of building track.
*/
public int getLength() {
return length;
}
public Iterator getPossibleConfigurationsIterator() {
return flatTrackConfigurations.iterator();
}
public int getTrackGraphicsID() {
return configuration;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final TrackConfiguration that = (TrackConfiguration) o;
if (configuration != that.configuration)
return false;
return true;
}
@Override
public int hashCode() {
return configuration;
}
private Object readResolve() throws ObjectStreamException {
return TrackConfiguration.from9bitTemplate(this.configuration);
}
/**
* Returns a String representing this configuration, for example "north,
* south".
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
int matches = 0;
if (contains(TrackConfiguration.getFlatInstance("000010000"))) {
sb.append("tile center");
} else {
sb.append("no tile center");
}
for (int i = 0; i < 8; i++) {
Step v = Step.getInstance(i);
if (contains(v)) {
sb.append(",");
sb.append(v);
matches++;
}
}
return sb.toString().trim();
}
}
Methods:
MethodJavadoc
add/**
contains
contains
from9bitTemplate
get8bitTemplate
get9bitTemplate/**
getFlatInstance
getFlatInstance
getLength/**
getPossibleConfigurationsIterator
getTrackGraphicsID
readResolve
setupConfigurations
stringTemplate2Int
subtract/**
jfreerails.world.track.TrackPiece
Javadoc:
/** * Defines methods to access the properties of the track on a tile. * * @author Luke */
Source code:
/**
* Defines methods to access the properties of the track on a tile.
*
* @author Luke
*/
public interface TrackPiece extends FreerailsSerializable {
int getTrackGraphicID();
int getTrackTypeID();
TrackRule getTrackRule();
TrackConfiguration getTrackConfiguration();
int getOwnerID();
}
Methods:
MethodJavadoc
getOwnerID
getTrackConfiguration
getTrackGraphicID
getTrackRule
getTrackTypeID
jfreerails.world.track.TrackPieceImpl
Javadoc:
/** * Represents the track on a tile. * * @author Luke */
Source code:
/**
* Represents the track on a tile.
*
* @author Luke
*/
final public class TrackPieceImpl implements TrackPiece {
private static final long serialVersionUID = 4049080423458027569L;
private final TrackConfiguration configuration;
private final TrackRule trackType;
private final int ownerID;
private final int ruleNumber;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final TrackPieceImpl that = (TrackPieceImpl) o;
if (ownerID != that.ownerID)
return false;
if (ruleNumber != that.ruleNumber)
return false;
if (!configuration.equals(that.configuration))
return false;
if (!trackType.equals(that.trackType))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = configuration.hashCode();
result = 29 * result + trackType.hashCode();
result = 29 * result + ownerID;
result = 29 * result + ruleNumber;
return result;
}
public TrackPieceImpl(TrackConfiguration c, TrackRule type, int owner,
int rule) {
configuration = c;
trackType = type;
ownerID = owner;
ruleNumber = rule;
}
public int getTrackGraphicID() {
return configuration.getTrackGraphicsID();
}
public TrackRule getTrackRule() {
return trackType;
}
public TrackConfiguration getTrackConfiguration() {
return configuration;
}
public int getOwnerID() {
return ownerID;
}
public int getTrackTypeID() {
return ruleNumber;
}
}
Methods:
MethodJavadoc
getOwnerID
getTrackConfiguration
getTrackGraphicID
getTrackRule
getTrackTypeID
jfreerails.world.track.TrackRule
Javadoc:
/** * Defines methods to access the properties of a track type. * * @author Luke Lindsay 09 October 2001 */
Source code:
/**
* Defines methods to access the properties of a track type.
*
* @author Luke Lindsay 09 October 2001
*/
public interface TrackRule extends FreerailsSerializable, Comparable<TrackRule> {
public enum TrackCategories {
track, bridge, tunnel, station, non
}
TrackCategories getCategory();
boolean canBuildOnThisTerrainType(TerrainType.Category TerrainType);
boolean isStation();
boolean isDouble();
Money getPrice();
Money getFixedCost();
Money getMaintenanceCost();
int getStationRadius();
String getTypeName();
boolean testTrackPieceLegality(int a9bitTemplate);
boolean trackPieceIsLegal(TrackConfiguration config);
int getMaximumConsecutivePieces();
Step[] getLegalRoutes(Step directionComingFrom);
Iterator<TrackConfiguration> getLegalConfigurationsIterator();
}
Methods:
MethodJavadoc
canBuildOnThisTerrainType
getCategory
getFixedCost
getLegalConfigurationsIterator
getLegalRoutes
getMaintenanceCost
getMaximumConsecutivePieces
getPrice
getStationRadius
getTypeName
isDouble
isStation
testTrackPieceLegality
trackPieceIsLegal/**
jfreerails.world.track.TrackRuleImpl
Javadoc:
/** * This class encapsulates the rules that apply to a type of track node. They * concern: the legal routes trains can travel across the node, whether the * node's track can be doubled, on which terrain types it can be built, and the * maximum number of consecutive nodes of this type (used for bridges and * tunnels). * * @author Luke Lindsay 09 October 2001 */
Source code:
/**
* This class encapsulates the rules that apply to a type of track node. They
* concern: the legal routes trains can travel across the node, whether the
* node's track can be doubled, on which terrain types it can be built, and the
* maximum number of consecutive nodes of this type (used for bridges and
* tunnels).
*
* @author Luke Lindsay 09 October 2001
*/
final public class TrackRuleImpl implements TrackRule {
private static final long serialVersionUID = 3257281414171801401L;
private final LegalTrackConfigurations legalConfigurations;
private final LegalTrackPlacement legalTrackPlacement;
private final TrackRuleProperties properties;
/*
* Track templates are 9 bit values, so there are 512 possible templates. If
* legalTrackTemplate[x]==true, then x is a legal track-template. Example:
* 000 111 000 This represents a horizontal straight.
*/
public TrackRuleImpl(TrackRuleProperties p, LegalTrackConfigurations lc,
LegalTrackPlacement ltp) {
if (null == p || null == lc || null == ltp) {
throw new java.lang.IllegalArgumentException();
}
properties = p;
legalConfigurations = lc;
legalTrackPlacement = ltp;
}
public boolean canBuildOnThisTerrainType(TerrainType.Category TerrainType) {
return legalTrackPlacement.canBuildOnThisTerrain(TerrainType);
}
/**
* If the specified object is a track rule, comparison is by category then
* price.
*/
public int compareTo(TrackRule otherRule) {
int comp = otherRule.getCategory().compareTo(getCategory());
if (comp != 0) {
return -comp;
}
long dPrice = this.properties.getPrice().getAmount()
- otherRule.getPrice().getAmount();
return (int) dPrice;
}
@Override
public boolean equals(Object o) {
if (o instanceof TrackRuleImpl) {
TrackRuleImpl trackRuleImpl = (TrackRuleImpl) o;
boolean propertiesFieldsEqual = this.properties
.equals(trackRuleImpl.getProperties());
boolean legalConfigurationsEqual = this.legalConfigurations
.equals(trackRuleImpl.getLegalConfigurations());
boolean legalTrackPlacementEqual = this.legalTrackPlacement
.equals(trackRuleImpl.getLegalTrackPlacement());
if (propertiesFieldsEqual && legalConfigurationsEqual
&& legalTrackPlacementEqual) {
return true;
}
return false;
}
return false;
}
public TrackRule.TrackCategories getCategory() {
return properties.getCategory();
}
public LegalTrackConfigurations getLegalConfigurations() {
return legalConfigurations;
}
public Iterator<TrackConfiguration> getLegalConfigurationsIterator() {
return legalConfigurations.getLegalConfigurationsIterator();
}
public Step[] getLegalRoutes(Step directionComingFrom) {
// TODO add code..
return null;
}
public LegalTrackPlacement getLegalTrackPlacement() {
return legalTrackPlacement;
}
public Money getMaintenanceCost() {
return properties.getMaintenanceCost();
}
public int getMaximumConsecutivePieces() {
return legalConfigurations.getMaximumConsecutivePieces();
}
public Money getPrice() {
return this.properties.getPrice();
}
public TrackRuleProperties getProperties() {
return properties;
}
public int getStationRadius() {
return this.properties.getStationRadius();
}
public String getTypeName() {
return properties.getTypeName();
}
@Override
public int hashCode() {
int result;
result = properties.hashCode();
result = 29 * result + legalConfigurations.hashCode();
result = 29 * result + legalTrackPlacement.hashCode();
return result;
}
public boolean isStation() {
return properties.isStation();
}
public boolean testTrackPieceLegality(int trackTemplateToTest) {
TrackConfiguration trackConfiguration = TrackConfiguration
.from9bitTemplate(trackTemplateToTest);
return legalConfigurations
.trackConfigurationIsLegal(trackConfiguration);
}
@Override
public String toString() {
return getTypeName();
}
public boolean trackPieceIsLegal(TrackConfiguration config) {
return legalConfigurations.trackConfigurationIsLegal(config);
}
public boolean isDouble() {
return properties.isEnableDoubleTrack();
}
public Money getFixedCost() {
return properties.getFixedCost();
}
}
Methods:
MethodJavadoc
canBuildOnThisTerrainType
compareTo/**
getCategory
getFixedCost
getLegalConfigurations
getLegalConfigurationsIterator
getLegalRoutes
getLegalTrackPlacement
getMaintenanceCost
getMaximumConsecutivePieces
getPrice
getProperties
getStationRadius
getTypeName
isDouble
isStation
testTrackPieceLegality
trackPieceIsLegal
jfreerails.world.track.TrackRuleProperties
Javadoc:
/** * Stores some of the properties of a track type. * * @author Luke */
Source code:
/**
* Stores some of the properties of a track type.
*
* @author Luke
*/
final public class TrackRuleProperties implements FreerailsSerializable {
private static final long serialVersionUID = 3618704101752387641L;
private final boolean enableDoubleTrack;
private final Money maintenanceCost;
private final Money price;
private final Money fixedCost;
private final TrackRule.TrackCategories category;
private final int rGBvalue;
private final int stationRadius;
private final String typeName;
public TrackRuleProperties(int rgb, boolean doubleTrack, String name,
TrackRule.TrackCategories c, int radius, int price,
int maintenance, int fixedCost) {
stationRadius = radius;
rGBvalue = rgb;
enableDoubleTrack = doubleTrack;
typeName = name;
category = c;
this.price = new Money(price);
this.maintenanceCost = new Money(maintenance);
this.fixedCost = new Money(fixedCost);
}
@Override
public boolean equals(Object o) {
if (o instanceof TrackRuleProperties) {
TrackRuleProperties test = (TrackRuleProperties) o;
if (rGBvalue == test.getRGBvalue()
&& enableDoubleTrack == test.isEnableDoubleTrack()
&& typeName.equals(test.getTypeName())
&& category == test.category
&& stationRadius == test.stationRadius) {
return true;
}
return false;
}
return false;
}
public Money getMaintenanceCost() {
return maintenanceCost;
}
public Money getPrice() {
return price;
}
private int getRGBvalue() {
return rGBvalue;
}
public int getStationRadius() {
return stationRadius;
}
public String getTypeName() {
return typeName;
}
@Override
public int hashCode() {
int result;
result = rGBvalue;
result = 29 * result + (enableDoubleTrack ? 1 : 0);
result = 29 * result + typeName.hashCode();
result = 29 * result + category.hashCode();
result = 29 * result + stationRadius;
result = 29 * result + price.hashCode();
result = 29 * result + fixedCost.hashCode();
result = 29 * result + maintenanceCost.hashCode();
return result;
}
public boolean isEnableDoubleTrack() {
return enableDoubleTrack;
}
public boolean isStation() {
return category.equals(TrackRule.TrackCategories.station);
}
public TrackRule.TrackCategories getCategory() {
return category;
}
public Money getFixedCost() {
return fixedCost;
}
}
Methods:
MethodJavadoc
getCategory
getFixedCost
getMaintenanceCost
getPrice
getRGBvalue
getStationRadius
getTypeName
isEnableDoubleTrack
isStation
jfreerails.world.track.TrackSection
Javadoc:
/** * Represents the track connecting two adjacent tiles. * * @author Luke * */
Source code:
/**
* Represents the track connecting two adjacent tiles.
*
* @author Luke
*
*/
public class TrackSection implements FreerailsSerializable {
private static final long serialVersionUID = -3776624056097990938L;
private final Step step;
private final ImPoint tile;
public TrackSection(final Step step, final ImPoint tile) {
ImPoint otherTile = Step.move(tile, step);
if(tile.compareTo(otherTile) > 0){
this.step = step.getOpposite();
this.tile = otherTile;
}else{
this.step = step;
this.tile = tile;
}
}
@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((step == null) ? 0 : step.hashCode());
result = PRIME * result + ((tile == null) ? 0 : tile.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final TrackSection other = (TrackSection) obj;
if (step == null) {
if (other.step != null)
return false;
} else if (!step.equals(other.step))
return false;
if (tile == null) {
if (other.tile != null)
return false;
} else if (!tile.equals(other.tile))
return false;
return true;
}
@Override
public String toString() {
return tile.toString()+ " "+ step.toString();
}
public ImPoint tileA(){
return tile;
}
public ImPoint tileB(){
return Step.move(tile, step);
}
}
Methods:
MethodJavadoc
tileA
tileB
jfreerails.world.train.CompositeSpeedAgainstTime
Javadoc:
/** * Represents a composite speed-time relationship composed of multiple {@link SpeedAgainstTime} segments. * This class aggregates individual speed-time data to compute overall duration, distance, and * instantaneous values (speed, acceleration) at any given time. It provides methods to calculate * cumulative distance, time, and state information based on the combined segments. * * @author [Your Name] * @see SpeedAgainstTime * @see Activity */
Source code:
public class CompositeSpeedAgainstTime implements Activity<SpeedTimeAndStatus>,
SpeedAgainstTime {
private static final long serialVersionUID = 3146586143114534610L;
private final ImList<SpeedAgainstTime> values;
private final double finalT, finalS;
public CompositeSpeedAgainstTime(SpeedAgainstTime... accs) {
values = new ImList<SpeedAgainstTime>(accs);
values.checkForNulls();
double tempDuration = 0, tempTotalDistance = 0;
for (int i = 0; i < accs.length; i++) {
tempDuration += accs[i].getT();
tempTotalDistance += accs[i].getS();
}
finalT = tempDuration;
finalS = tempTotalDistance;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof CompositeSpeedAgainstTime))
return false;
final CompositeSpeedAgainstTime compositeSpeedAgainstTime = (CompositeSpeedAgainstTime) o;
if (finalT != compositeSpeedAgainstTime.finalT)
return false;
if (finalS != compositeSpeedAgainstTime.finalS)
return false;
if (!values.equals(compositeSpeedAgainstTime.values))
return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
result = values.hashCode();
temp = finalT != +0.0d ? Double.doubleToLongBits(finalT) : 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
temp = finalS != +0.0d ? Double.doubleToLongBits(finalS)
: 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
return result;
}
public double duration() {
return finalT;
}
public SpeedTimeAndStatus getState(final double dt) {
checkT(dt);
double acceleration;
SpeedTimeAndStatus.TrainActivity activity = SpeedTimeAndStatus.TrainActivity.READY;
double s = 0;
double speed;
TandI tai = getIndex(dt);
SpeedAgainstTime acc = values.get(tai.i);
speed = acc.calcV(tai.offset);
acceleration = acc.calcA(tai.offset);
s = acc.calcS(tai.offset);
return new SpeedTimeAndStatus(acceleration, activity, dt, s, speed);
}
public double calcS(double t) {
if(t == this.finalT) return this.finalS;
checkT(t);
TandI tai = getIndex(t);
double s = 0;
for (int i = 0; i < tai.i; i++) {
SpeedAgainstTime acc = values.get(i);
s += acc.getS();
}
SpeedAgainstTime acc = values.get(tai.i);
if(tai.offset >= acc.getT()){
//Note, it is possible for tai.offset > acc.getT()
//even though we called checkT(t) above
s += acc.getS();
}else{
s += acc.calcS(tai.offset);
}
return s;
}
public double calcT(double s) {
if(s == this.finalS) return this.finalT;
if (s > finalS)
throw new IllegalArgumentException(String.valueOf(s));
double sSoFar = 0;
double tSoFar = 0;
int i = 0;
SpeedAgainstTime acc = values.get(i);
while ((sSoFar + acc.getS()) < s) {
sSoFar += acc.getS();
tSoFar += acc.getT();
i++;
acc = values.get(i);
}
double sOffset = s - sSoFar;
if(sOffset >= acc.getS()){
tSoFar += acc.getT();
}else{
tSoFar += acc.calcT(sOffset);
}
return tSoFar;
}
public double calcV(double t) {
checkT(t);
TandI tai = getIndex(t);
SpeedAgainstTime acc = values.get(tai.i);
return acc.calcV(tai.offset);
}
public double calcA(double t) {
checkT(t);
TandI tai = getIndex(t);
SpeedAgainstTime acc = values.get(tai.i);
return acc.calcA(tai.offset);
}
public double getT() {
return finalT;
}
public double getS() {
return finalS;
}
private TandI getIndex(double t) {
checkT(t);
double tSoFar = 0;
for (int i = 0; i < values.size(); i++) {
SpeedAgainstTime acc = values.get(i);
if (t <= (tSoFar + acc.getT())) {
double offset = t - tSoFar;
return new TandI(i, offset);
}
tSoFar += acc.getT();
}
// Should never happen since we call checkT() above!
throw new IllegalStateException(String.valueOf(t));
}
/** Used to enable 2 values to be returned from the method getIndex(double t) */
private static class TandI {
final double offset;
final int i;
TandI(int i, double t) {
this.i = i;
this.offset = t;
}
}
void checkT(double t) {
if (t < 0d || t > finalT)
throw new IllegalArgumentException("t="+t+", but duration="+finalT);
}
}
Methods:
MethodJavadoc
calcA
calcS
calcT
calcV
checkT
duration
getIndex
getS
getState
getT
jfreerails.world.train.ConstAcc
Javadoc:
/** * Represents motion under constant acceleration, providing methods to calculate position, velocity, time, and other kinematic properties. * This class encapsulates the parameters of constant acceleration motion (initial velocity, acceleration, final time, and final position) * and includes utility methods to compute derived values based on time or displacement. * * @author John Doe * @since 1.0 * * @see FreerailsSerializable * @see SpeedAgainstTime */
Source code:
strictfp public class ConstAcc implements FreerailsSerializable,
SpeedAgainstTime {
private static final long serialVersionUID = -2180666310811530761L;
public static final ConstAcc STOPPED = new ConstAcc(0, 0, 0, 0);
public static ConstAcc uas(double u, double a, double s) {
double t = calcT(u, a, s);
return new ConstAcc(a, t, u, s);
}
private static double calcT(double u, double a, double s) {
// Note, Utils.solveQuadratic throws an exception if a == 0
return a == 0 ? s / u : Utils.solveQuadratic(a * 0.5d, u, -s);
}
public static ConstAcc uat(double u, double a, double t) {
double s = u * t + a * t * t / 2;
return new ConstAcc(a, t, u, s);
}
private final double u, a, finalS, finalT;
private ConstAcc(double a, double t, double u, double s) {
this.a = a;
this.finalT = t;
this.u = u;
this.finalS = s;
}
public double calcS(double t) {
if(t == finalT) return finalS;
validateT(t);
double ds = u * t + a * t * t / 2;
ds = Math.min(ds, finalS);
return ds;
}
public double calcT(double s) {
if(s == finalS ) return finalT;
if(s < 0 || s > this.finalS )
throw new IllegalArgumentException(s+" < 0 || "+s+" > "+finalS );
double returnValue = calcT(u, a, s);
returnValue = Math.min(returnValue, finalT);
return returnValue;
}
public double calcV(double t) {
validateT(t);
return u + a * t;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ConstAcc))
return false;
final ConstAcc constAcc = (ConstAcc) o;
if (a != constAcc.a)
return false;
if (finalT != constAcc.finalT)
return false;
if (u != constAcc.u)
return false;
return true;
}
public double calcA(double t) {
validateT(t);
return a;
}
public double getT() {
return finalT;
}
public double getS() {
return finalS;
}
@Override
public int hashCode() {
int result;
long temp;
temp = u != +0.0d ? Double.doubleToLongBits(u) : 0l;
result = (int) (temp ^ (temp >>> 32));
temp = a != +0.0d ? Double.doubleToLongBits(a) : 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
temp = finalT != +0.0d ? Double.doubleToLongBits(finalT) : 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
return result;
}
private void validateT(double t){
if(t < 0 || t > finalT)
throw new IllegalArgumentException("("+t+" < 0 || "+t+" > "+finalT+")");
}
@Override
public String toString() {
String str = "ConstAcc [a=" + a + ", u=" + u + ", dt=" + finalT + "]";
return str;
}
}
Methods:
MethodJavadoc
calcA
calcS
calcT
calcT
calcV
getS
getT
uas
uat
validateT
jfreerails.world.train.EngineType
Javadoc:
/** * This class represents an engine type, for example 'Grass Hopper'. It * encapsulates the properties that are common to all engines of the same type. * * @author Luke * */
Source code:
/**
* This class represents an engine type, for example 'Grass Hopper'. It
* encapsulates the properties that are common to all engines of the same type.
*
* @author Luke
*
*/
final public class EngineType implements FreerailsSerializable {
private static final long serialVersionUID = 3617014130905592630L;
private final String engineTypeName;
private final Money maintenance;
private final int maxSpeed; // speed in mph
private final int powerAtDrawbar;
private final Money price;
public EngineType(String name, int power, Money m, int speed) {
engineTypeName = name;
powerAtDrawbar = power;
price = m;
maxSpeed = speed;
maintenance = new Money(0);
}
public EngineType(String name, int power, Money m, int speed, Money maint) {
engineTypeName = name;
powerAtDrawbar = power;
price = m;
maxSpeed = speed;
maintenance = maint;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof EngineType))
return false;
EngineType other = (EngineType) obj;
return engineTypeName.equals(other.engineTypeName)
&& powerAtDrawbar == other.powerAtDrawbar && price.equals(other.price)
&& maintenance.equals(other.maintenance)
&& maxSpeed == other.maxSpeed;
}
public String getEngineTypeName() {
return engineTypeName;
}
public Money getMaintenance() {
return maintenance;
}
public int getMaxSpeed() {
return maxSpeed;
}
public int getPowerAtDrawbar() {
return powerAtDrawbar;
}
public Money getPrice() {
return price;
}
@Override
public int hashCode() {
int result;
result = powerAtDrawbar;
result = 29 * result + engineTypeName.hashCode();
result = 29 * result + price.hashCode();
result = 29 * result + maintenance.hashCode();
result = 29 * result + maxSpeed;
return result;
}
@Override
public String toString() {
return engineTypeName;
}
}
Methods:
MethodJavadoc
getEngineTypeName
getMaintenance
getMaxSpeed
getPowerAtDrawbar
getPrice
jfreerails.world.train.ImmutableSchedule
Javadoc:
/** * A Schedule that is immutable. * * @author Luke Lindsay * */
Source code:
/**
* A Schedule that is immutable.
*
* @author Luke Lindsay
*
*/
public class ImmutableSchedule implements Schedule, FreerailsSerializable {
private static final long serialVersionUID = 3977858458324318264L;
private final ImList<TrainOrdersModel> orders;
private final int nextScheduledOrder;
@Override
public int hashCode() {
int result;
result = nextScheduledOrder;
result = 29 * result + (hasPriorityOrders ? 1 : 0);
return result;
}
private final boolean hasPriorityOrders;
public ImmutableSchedule(TrainOrdersModel[] orders, int gotoStation,
boolean hasPriorityOrders) {
this.orders = new ImList<TrainOrdersModel>(orders);
this.nextScheduledOrder = gotoStation;
this.hasPriorityOrders = hasPriorityOrders;
}
public TrainOrdersModel getOrder(int i) {
return orders.get(i);
}
public int getOrderToGoto() {
return hasPriorityOrders ? 0 : nextScheduledOrder;
}
public int getStationToGoto() {
int orderToGoto = getOrderToGoto();
if (-1 == orderToGoto) {
return -1;
}
TrainOrdersModel order = orders.get(orderToGoto);
return order.getStationID();
}
public ImInts getWagonsToAdd() {
TrainOrdersModel order = orders.get(getOrderToGoto());
return order.consist;
}
public boolean hasPriorityOrders() {
return hasPriorityOrders;
}
public int getNumOrders() {
return orders.size();
}
public int getNextScheduledOrder() {
return this.nextScheduledOrder;
}
public boolean stopsAtStation(int stationNumber) {
for (int i = 0; i < this.getNumOrders(); i++) {
TrainOrdersModel order = this.getOrder(i);
if (order.getStationID() == stationNumber) {
return true;
}
}
return false;
}
@Override
public boolean equals(Object o) {
if (o instanceof ImmutableSchedule) {
ImmutableSchedule test = (ImmutableSchedule) o;
return this.hasPriorityOrders == test.hasPriorityOrders
&& this.nextScheduledOrder == test.nextScheduledOrder
&& this.orders.equals(test.orders);
}
return false;
}
public boolean autoConsist() {
TrainOrdersModel order = orders.get(getOrderToGoto());
return order.autoConsist;
}
}
Methods:
MethodJavadoc
autoConsist
getNextScheduledOrder
getNumOrders
getOrder
getOrderToGoto
getStationToGoto/**
getWagonsToAdd
hasPriorityOrders
stopsAtStation
jfreerails.world.train.MutableSchedule
Javadoc:
/** * This class represents a train's schedule. That is, which stations that the * train should visit and what wagons the engine should pull. * * @author lindsal */
Source code:
/**
* This class represents a train's schedule. That is, which stations that the
* train should visit and what wagons the engine should pull.
*
* @author lindsal
*/
public class MutableSchedule implements Schedule {
/**
* Vector of TrainOrdersModel.
*/
private final Vector<TrainOrdersModel> orders = new Vector<TrainOrdersModel>();
private int nextScheduledOrder = -1;
/**
* Whether the train should ignore the stationToGoto and goto the first
* station in the list.
*/
private boolean hasPriorityOrders = false;
public MutableSchedule() {
}
public MutableSchedule(ImmutableSchedule s) {
nextScheduledOrder = s.getNextScheduledOrder();
hasPriorityOrders = s.hasPriorityOrders();
for (int i = 0; i < s.getNumOrders(); i++) {
orders.add(s.getOrder(i));
}
}
public ImmutableSchedule toImmutableSchedule() {
TrainOrdersModel[] ordersArray = new TrainOrdersModel[orders.size()];
for (int i = 0; i < ordersArray.length; i++) {
ordersArray[i] = orders.get(i);
}
return new ImmutableSchedule(ordersArray, this.nextScheduledOrder,
this.hasPriorityOrders);
}
public void setPriorityOrders(TrainOrdersModel order) {
if (hasPriorityOrders) {
// Replace existing priority orders.
orders.set(PRIORITY_ORDERS, order);
} else {
// Insert priority orders at position 0;
hasPriorityOrders = true;
orders.add(PRIORITY_ORDERS, order);
nextScheduledOrder++;
}
}
/**
* Removes the order at the specified position.
*/
public void removeOrder(int orderNumber) {
if (PRIORITY_ORDERS == orderNumber && hasPriorityOrders) {
// If we are removing the priority stop.
hasPriorityOrders = false;
}
orders.remove(orderNumber);
/* shift current station down */
if (nextScheduledOrder > orderNumber) {
nextScheduledOrder--;
}
if (orders.size() <= nextScheduledOrder) {
nextScheduledOrder = firstScheduleStop();
}
if (0 == numberOfScheduledStops()) {
nextScheduledOrder = -1;
}
}
private int firstScheduleStop() {
return hasPriorityOrders ? 1 : 0;
}
private int numberOfScheduledStops() {
return orders.size() - firstScheduleStop();
}
/**
* Inserts an order at the specified position. Note you must call
* setPriorityOrders() to set the priority orders.
*/
public void addOrder(int orderNumber, TrainOrdersModel order) {
orders.add(orderNumber, order);
if (nextScheduledOrder >= orderNumber) {
nextScheduledOrder++;
}
if (-1 == nextScheduledOrder && 0 < numberOfScheduledStops()) {
nextScheduledOrder = firstScheduleStop();
}
}
public int addOrder(TrainOrdersModel order) {
if (!canAddOrder()) {
throw new IllegalStateException();
}
int newOrderNumber = orders.size();
addOrder(newOrderNumber, order);
return newOrderNumber;
}
public void setOrder(int orderNumber, TrainOrdersModel order) {
if (orderNumber >= orders.size()) {
orders.add(order);
} else {
orders.set(orderNumber, order);
}
}
public TrainOrdersModel getOrder(int i) {
return orders.get(i);
}
/** Returns the number of the order the train is currently carry out. */
public int getOrderToGoto() {
return nextScheduledOrder;
}
public void setOrderToGoto(int i) {
if (i < 0 || i >= orders.size()) {
throw new IllegalArgumentException(String.valueOf(i));
}
nextScheduledOrder = i;
}
/**
* Returns the station number of the next station the train is scheduled to
* stop at.
*/
public int getStationToGoto() {
return orders.get(nextScheduledOrder).getStationID();
}
/** Returns the wagons to add at the next scheduled stop. */
public ImInts getWagonsToAdd() {
return orders.get(nextScheduledOrder).getConsist();
}
/**
* If there are no priority orders, sets the station to goto to the next
* station in the list of orders or if there are no more stations, the first
* station in the list. If priority orders are set, the priority orders
* orders are removed from the schedule and the goto station is not changed.
*/
public void gotoNextStation() {
if (hasPriorityOrders) {
if (nextScheduledOrder != PRIORITY_ORDERS) {
removeOrder(PRIORITY_ORDERS);
return;
}
}
nextScheduledOrder++;
if (orders.size() <= nextScheduledOrder) {
nextScheduledOrder = 0;
}
}
public boolean hasPriorityOrders() {
return this.hasPriorityOrders;
}
/**
* Returns number of non priority orders + number of priority orders.
*
* @return Number of orders.
*/
public int getNumOrders() {
return orders.size();
}
public boolean canPullUp(int orderNumber) {
boolean isAlreadyAtTop = 0 == orderNumber;
boolean isPriorityOrdersAbove = (orderNumber == 1 && this.hasPriorityOrders);
return !isAlreadyAtTop && !isPriorityOrdersAbove;
}
public boolean canPushDown(int orderNumber) {
boolean isOrderPriorityOrders = (orderNumber == 0 && this.hasPriorityOrders);
boolean isAlreadyAtBottom = orderNumber == this.orders.size() - 1;
return !isOrderPriorityOrders && !isAlreadyAtBottom;
}
public void pullUp(int orderNumber) {
if (!canPullUp(orderNumber)) {
throw new IllegalArgumentException(String.valueOf(orderNumber));
}
boolean isGoingToThisStation = getOrderToGoto() == orderNumber;
TrainOrdersModel order = getOrder(orderNumber);
removeOrder(orderNumber);
addOrder(orderNumber - 1, order);
if (isGoingToThisStation) {
setOrderToGoto(orderNumber - 1);
}
}
public void pushDown(int orderNumber) {
if (!canPushDown(orderNumber)) {
throw new IllegalArgumentException(String.valueOf(orderNumber));
}
boolean isGoingToThisStation = getOrderToGoto() == orderNumber;
TrainOrdersModel order = getOrder(orderNumber);
removeOrder(orderNumber);
addOrder(orderNumber + 1, order);
if (isGoingToThisStation) {
setOrderToGoto(orderNumber + 1);
}
}
public boolean canAddOrder() {
int max = hasPriorityOrders ? MAXIMUM_NUMBER_OF_ORDER + 1
: MAXIMUM_NUMBER_OF_ORDER;
return max > getNumOrders();
}
public boolean canSetGotoStation(int orderNumber) {
return !(orderNumber == 0 && hasPriorityOrders);
}
public int getNextScheduledOrder() {
return this.nextScheduledOrder;
}
public void removeAllStopsAtStation(int stationNumber) {
int i = 0;
while (i < this.getNumOrders()) {
TrainOrdersModel order = this.getOrder(i);
if (order.getStationID() == stationNumber) {
this.removeOrder(i);
} else {
i++;
}
}
}
public boolean autoConsist() {
return orders.get(nextScheduledOrder).autoConsist;
}
}
Methods:
MethodJavadoc
addOrder
addOrder/**
autoConsist
canAddOrder
canPullUp
canPushDown
canSetGotoStation
firstScheduleStop
getNextScheduledOrder
getNumOrders/**
getOrder
getOrderToGoto/** Returns the number of the order the train is currently carry out. */
getStationToGoto/**
getWagonsToAdd/** Returns the wagons to add at the next scheduled stop. */
gotoNextStation/**
hasPriorityOrders
numberOfScheduledStops
pullUp
pushDown
removeAllStopsAtStation
removeOrder/**
setOrder
setOrderToGoto
setPriorityOrders
toImmutableSchedule
jfreerails.world.train.PathOnTiles
Javadoc:
/** * An immutable class that stores a path made up of OneTileMoveVectors. * * @author Luke * */
Source code:
/**
* An immutable class that stores a path made up of OneTileMoveVectors.
*
* @author Luke
*
*/
strictfp public class PathOnTiles implements FreerailsSerializable {
private static final long serialVersionUID = 3544386994122536753L;
private final ImPoint start;
private final ImList<Step> vectors;
/**
* @throws NullPointerException
* if null == start
* @throws NullPointerException
* if null == vectorsList
* @throws NullPointerException
* if null == vectorsList.get(i) for any i;
*/
public PathOnTiles(ImPoint start, List<Step> vectorsList) {
if (null == start)
throw new NullPointerException();
vectors = new ImList<Step>(vectorsList);
vectors.checkForNulls();
this.start = start;
}
/**
* @throws NullPointerException
* if null == start
* @throws NullPointerException
* if null == vectors
* @throws NullPointerException
* if null == vectors[i] for any i;
*/
public PathOnTiles(ImPoint start, Step... vectors) {
if (null == start)
throw new NullPointerException();
this.vectors = new ImList<Step>(vectors);
this.vectors.checkForNulls();
this.start = start;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof PathOnTiles))
return false;
final PathOnTiles pathOnTiles = (PathOnTiles) o;
if (!start.equals(pathOnTiles.start))
return false;
if (!vectors.equals(pathOnTiles.vectors))
return false;
return true;
}
/**
* Returns the distance you would travel if you walked the all the way along
* the path.
*/
public double getTotalDistance() {
return getDistance(vectors.size());
}
public double getDistance(int steps) {
double distanceSoFar = 0;
for (int i = 0; i < steps; i++) {
Step v = vectors.get(i);
distanceSoFar += v.getLength();
}
return distanceSoFar;
}
/**
* Returns the coordinates of the point you would be standing at if you
* walked the specified distance along the path from the start point.
*
* @throws IllegalArgumentException
* if distance < 0
* @throws IllegalArgumentException
* if distance > getLength()
*/
public ImPoint getPoint(double distance) {
if (0 > distance)
throw new IllegalArgumentException("distance:" + distance + " < 0");
int x = start.x * TILE_DIAMETER + TILE_DIAMETER / 2;
int y = start.y * TILE_DIAMETER + TILE_DIAMETER / 2;
double distanceSoFar = 0;
for (int i = 0; i < vectors.size(); i++) {
Step v = vectors.get(i);
distanceSoFar += v.getLength();
x += v.deltaX * TILE_DIAMETER;
y += v.deltaY * TILE_DIAMETER;
if (distanceSoFar == distance) {
return new ImPoint(x, y);
}
if (distanceSoFar > distance) {
double excess = distanceSoFar - distance;
x -= v.deltaX * TILE_DIAMETER * excess / v.getLength();
y -= v.deltaY * TILE_DIAMETER * excess / v.getLength();
return new ImPoint(x, y);
}
}
throw new IllegalArgumentException("distance > getLength()");
}
public ImPoint getStart() {
return start;
}
public Step getStep(int i) {
return vectors.get(i);
}
public PositionOnTrack getFinalPosition() {
int x = start.x;
int y = start.y;
for (int i = 0; i < vectors.size(); i++) {
Step v = vectors.get(i);
x += v.deltaX;
y += v.deltaY;
}
int i = vectors.size() - 1;
Step finalStep = vectors.get(i);
PositionOnTrack p = PositionOnTrack.createFacing(x, y, finalStep);
return p;
}
/**
* Returns the index of the step that takes the distance travelled over the
* specified distance.
*
* @throws IllegalArgumentException
* if distance < 0
* @throws IllegalArgumentException
* if distance > getLength()
*/
public int getStepIndex(int distance) {
if (0 > distance)
throw new IllegalArgumentException("distance < 0");
int distanceSoFar = 0;
for (int i = 0; i < vectors.size(); i++) {
Step v = vectors.get(i);
distanceSoFar += v.getLength();
if (distanceSoFar >= distance)
return i;
}
throw new IllegalArgumentException("distance > getLength()");
}
@Override
public int hashCode() {
return start.hashCode();
}
public int steps() {
return vectors.size();
}
public PathOnTiles addSteps(Step... newSteps) {
int oldLength = vectors.size();
Step[] newPath = new Step[oldLength + newSteps.length];
for (int i = 0; i < oldLength; i++) {
newPath[i] = vectors.get(i);
}
for (int i = 0; i < newSteps.length; i++) {
newPath[i + oldLength] = newSteps[i];
}
return new PathOnTiles(start, newPath);
}
/**
* Returns a FreerailsPathIterator that exposes a sub section of the path
* this object represents.
*
* @throws IllegalArgumentException
* if offset < 0
* @throws IllegalArgumentException
* if length <= 0
* @throws IllegalArgumentException
* if offset + length > getLength()
*
*/
public FreerailsPathIterator subPath(double offset, double length) {
if (offset < 0)
throw new IllegalArgumentException();
if (length <= 0)
throw new IllegalArgumentException();
if ((offset + length) > getTotalDistance())
throw new IllegalArgumentException(offset +" + "+ length+" > " +getTotalDistance());
final LinkedList<ImPoint> points = new LinkedList<ImPoint>();
ImPoint tile = getStart();
int tileX = tile.x;
int tileY = tile.y;
int distanceSoFar = 0;
for (int i = 0; i < vectors.size(); i++) {
if (distanceSoFar > offset + length) {
break;
}
if (distanceSoFar >= offset) {
int x = TILE_DIAMETER / 2 + TILE_DIAMETER * tileX;
int y = TILE_DIAMETER / 2 + TILE_DIAMETER * tileY;
points.add(new ImPoint(x, y));
}
Step v = vectors.get(i);
tileX += v.deltaX;
tileY += v.deltaY;
distanceSoFar += v.getLength();
}
ImPoint first = getPoint(offset);
if (points.size() == 0) {
points.addFirst(first);
} else if (!points.getFirst().equals(first)) {
points.addFirst(first);
}
ImPoint last = getPoint(offset + length);
if (!points.getLast().equals(last)) {
points.addLast(last);
}
return new FreerailsPathIterator() {
private static final long serialVersionUID = 1L;
int index = 0;
public boolean hasNext() {
return (index + 1) < points.size();
}
public void nextSegment(IntLine line) {
if (!hasNext()) {
throw new NoSuchElementException();
}
ImPoint a = points.get(index);
line.x1 = a.x;
line.y1 = a.y;
ImPoint b = points.get(index + 1);
line.x2 = b.x;
line.y2 = b.y;
index++;
}
};
}
public Iterator<ImPoint> tiles() {
return new Iterator<ImPoint>() {
int index = 0;
ImPoint next = start;
public boolean hasNext() {
return next != null;
}
public ImPoint next() {
if (next == null)
throw new NoSuchElementException();
ImPoint returnValue = next;
int x = next.x;
int y = next.y;
if (index < vectors.size()) {
Step s = vectors.get(index);
x += s.deltaX;
y += s.deltaY;
next = new ImPoint(x, y);
} else {
next = null;
}
index++;
return returnValue;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer(getClass().getName());
sb.append("{");
sb.append(start.x);
sb.append(", ");
sb.append(start.y);
for (int i = 0; i < vectors.size(); i++) {
sb.append(", ");
sb.append(vectors.get(i));
}
sb.append("}");
return sb.toString();
}
}
Methods:
MethodJavadoc
addSteps
getDistance/**
getFinalPosition
getPoint/**
getStart
getStep
getStepIndex/**
getTotalDistance/**
steps
subPath/**
tiles
jfreerails.world.train.PathWalker
Javadoc:
/** * This interface lets the caller retrieve a path broken into a series of steps, * whose length the caller specifies. E.g. it could be used to get the sub * section of a path that a train travels during an given time interval. * * @author Luke */
Source code:
/**
* This interface lets the caller retrieve a path broken into a series of steps,
* whose length the caller specifies. E.g. it could be used to get the sub
* section of a path that a train travels during an given time interval.
*
* @author Luke
*/
public interface PathWalker extends FreerailsPathIterator,
FreerailsMutableSerializable {
/**
* Returns true if we have not reached the end of the path.
*/
boolean canStepForward();
/**
* Moves this path walker forward by the specified distance along the path
* and returns a path iterator to retrieve the section of the path travelled
* during this move.
*/
void stepForward(double distance);
}
Methods:
MethodJavadoc
canStepForward/**
stepForward/**
jfreerails.world.train.PathWalkerImpl
Javadoc:
/** * PathWalker that walks the path exposed by a FreerailsPathIterator. * * @author Luke */
Source code:
/**
* PathWalker that walks the path exposed by a FreerailsPathIterator.
*
* @author Luke
*/
public class PathWalkerImpl implements PathWalker {
private static final long serialVersionUID = 4050204158701155639L;
private final FreerailsPathIterator it;
/**
* current segment of the path we are on.
*/
private final IntLine currentSegment = new IntLine();
private double distanceAlongCurrentSegment = 0;
private double distanceOfThisStepRemaining = 0;
private boolean beforeFirst = true;
private int lastX;
private int lastY;
public PathWalkerImpl(FreerailsPathIterator i) {
it = i;
}
/**
* @return true if we still have more of the current segment, or more
* segments left.
*/
public boolean canStepForward() {
if (currentSegment.getLength() > distanceAlongCurrentSegment) {
return true;
} else if (it.hasNext()) {
return true;
} else {
return false;
}
}
/**
* Specify the distance this PathWalker is to progress along the current
* step.
*/
public void stepForward(double distance) {
distanceOfThisStepRemaining += distance;
}
/**
* @return true if there is still some distance to go along this path
*/
public boolean hasNext() {
if (0 == distanceOfThisStepRemaining) {
return false;
} else if (distanceAlongCurrentSegment < currentSegment.getLength()) {
return true;
} else if (it.hasNext()) {
return true;
} else {
return false;
}
}
public void nextSegment(IntLine line) {
if (!hasNext()) {
throw new NoSuchElementException();
}
// If we are at the end of the current segment, start a new one.
if (currentSegment.getLength() <= distanceAlongCurrentSegment) {
startNewSegment(line);
} else {
startInMiddleOfSegment(line);
}
double remainingDistanceAlongCurrentSegment = currentSegment
.getLength()
- distanceAlongCurrentSegment;
if (distanceOfThisStepRemaining > remainingDistanceAlongCurrentSegment) {
endAtSegmentEnd(line, remainingDistanceAlongCurrentSegment);
} else {
endInMiddleOfSegment(line);
}
/*
* Sanity check: the first point of the last line should equal the
* second point of the current line.
*
*/
if (!beforeFirst) {
if (line.x1 != this.lastX) {
throw new IllegalStateException();
}
if (line.y1 != this.lastY) {
throw new IllegalStateException();
}
}
this.lastX = line.x2;
this.lastY = line.y2;
beforeFirst = false;
return;
}
private void endInMiddleOfSegment(IntLine line) {
distanceAlongCurrentSegment += distanceOfThisStepRemaining;
distanceOfThisStepRemaining = 0;
line.x2 = getCoordinateOnSegment(distanceAlongCurrentSegment,
currentSegment.x1, currentSegment.x2);
line.y2 = getCoordinateOnSegment(distanceAlongCurrentSegment,
currentSegment.y1, currentSegment.y2);
}
private void endAtSegmentEnd(IntLine line,
double remainingDistanceAlongCurrentSegment) {
line.x2 = this.currentSegment.x2;
line.y2 = this.currentSegment.y2;
this.distanceOfThisStepRemaining -= remainingDistanceAlongCurrentSegment;
distanceAlongCurrentSegment = this.currentSegment.getLength();
}
private void startInMiddleOfSegment(IntLine line) {
line.x1 = getCoordinateOnSegment(distanceAlongCurrentSegment,
currentSegment.x1, currentSegment.x2);
line.y1 = getCoordinateOnSegment(distanceAlongCurrentSegment,
currentSegment.y1, currentSegment.y2);
}
private void startNewSegment(IntLine line) {
it.nextSegment(currentSegment);
distanceAlongCurrentSegment = 0;
line.x1 = this.currentSegment.x1;
line.y1 = this.currentSegment.y1;
}
private int getCoordinateOnSegment(double distanceAlongSegment,
int coordinate1, int coordinate2) {
double segmentLength = this.currentSegment.getLength();
double delta = 0;
if (0 != segmentLength) {
delta = (coordinate2 - coordinate1) * distanceAlongSegment
/ segmentLength;
}
return coordinate1 + (int) delta;
}
}
Methods:
MethodJavadoc
canStepForward/**
endAtSegmentEnd
endInMiddleOfSegment/**
getCoordinateOnSegment
hasNext/**
nextSegment
startInMiddleOfSegment
startNewSegment
stepForward/**
jfreerails.world.train.Schedule
Javadoc:
/** * Defines methods to access a train's schedule. * * @author Luke Lindsay * */
Source code:
/**
* Defines methods to access a train's schedule.
*
* @author Luke Lindsay
*
*/
public interface Schedule {
public static int PRIORITY_ORDERS = 0;
public static final int MAXIMUM_NUMBER_OF_ORDER = 6;
TrainOrdersModel getOrder(int i);
/** Returns the number of the order the train is currently carry out. */
int getOrderToGoto();
/**
* Returns the station number of the next station the train is scheduled to
* stop at.
*/
int getStationToGoto();
/** Returns the wagons to add at the next scheduled stop. */
ImInts getWagonsToAdd();
/** Returns the value for the autoconsist flag at the next scheduled stop. */
boolean autoConsist();
boolean hasPriorityOrders();
/**
* Returns number of non priority orders + number of priority orders.
*
* @return Number of orders.
*/
int getNumOrders();
int getNextScheduledOrder();
}
Methods:
MethodJavadoc
autoConsist/** Returns the value for the autoconsist flag at the next scheduled stop. */
getNextScheduledOrder
getNumOrders/**
getOrder
getOrderToGoto/** Returns the number of the order the train is currently carry out. */
getStationToGoto/**
getWagonsToAdd/** Returns the wagons to add at the next scheduled stop. */
hasPriorityOrders
jfreerails.world.train.SimplePathIteratorImpl
Javadoc:
/** * Exposes a path stored as an array of x points and an array of y points. * * @author Luke */
Source code:
/**
* Exposes a path stored as an array of x points and an array of y points.
*
* @author Luke
*/
public class SimplePathIteratorImpl implements FreerailsPathIterator {
private static final long serialVersionUID = 3618420406261003576L;
private final ImInts x;
private final ImInts y;
private int position = 0;
public SimplePathIteratorImpl(ImInts xpoints, ImInts ypoints) {
x = xpoints;
y = ypoints;
if (x.size() != y.size()) {
throw new IllegalArgumentException(
"The array length of the array must be even");
}
}
public SimplePathIteratorImpl( /* =const */
int[] xpoints, /* =const */
int[] ypoints) {
x = new ImInts(xpoints);
y = new ImInts(ypoints); // defensive copy.
if (x.size() != y.size()) {
throw new IllegalArgumentException(
"The array length of the array must be even");
}
}
public void nextSegment(IntLine line) {
if (hasNext()) {
line.x1 = x.get(position);
line.y1 = y.get(position);
line.x2 = x.get(position + 1);
line.y2 = y.get(position + 1);
position++;
} else {
throw new NoSuchElementException();
}
}
public boolean hasNext() {
return (position + 1) < x.size();
}
}
Methods:
MethodJavadoc
hasNext
nextSegment
jfreerails.world.train.SpeedAgainstTime
Javadoc:
/** * Represents a model of distance traveled over time, providing methods to calculate * distance from time, time from distance, and derived quantities such as velocity and * acceleration. This interface defines the contract for objects that represent the * relationship between time and distance, ensuring valid input ranges and throwing * exceptions for invalid parameters. * * @see FreerailsSerializable */
Source code:
public interface SpeedAgainstTime extends FreerailsSerializable {
/**
* Returns the distance travelled at time t. The returned value, s,
* satisfies the following conditions:
* <ol>
* <li>s >= 0</li>
* <li>s <= getS()</li>
* <li>s = 0 if t = 0 </li>
* <li>s = getS() if t = getT()</li>
* </ol>
*
* @throws IllegalArgumentException
* iff t < 0 or t > getT()
* @return s
*/
double calcS(double t);
/**
* Returns the time taken to travel distance s. The returned value, t,
* satisfies the following conditions:
* <ol>
* <li>t >= 0</li>
* <li>t <= getT()</li>
* <li>t = 0 if s = 0 </li>
* <li>t = getT() if s = getS()</li>
* </ol>
*
* @throws IllegalArgumentException
* iff s < 0 or s > getS()
* @return t
*/
double calcT(double s);
/**
* @throws IllegalArgumentException
* iff t < 0 or t > getT()
*/
double calcV(double t);
/**
* @throws IllegalArgumentException
* iff t < 0 or t > getT()
*/
double calcA(double t);
/**
* @return The time taken to travel the distance given by getS().
*/
double getT();
/**
* @return The distance traveled during at time given by getT().
*/
double getS();
}
Methods:
MethodJavadoc
calcA/**
calcS/**
calcT/**
calcV/**
getS/**
getT/**
jfreerails.world.train.SpeedTimeAndStatus
Javadoc:
/** * Stores the speed and status of a train immediately after an instant of time. * * @author Luke * */
Source code:
/**
* Stores the speed and status of a train immediately after an instant of time.
*
* @author Luke
*
*/
public class SpeedTimeAndStatus implements FreerailsSerializable {
private static final long serialVersionUID = 1L;
public enum TrainActivity {
STOPPED_AT_STATION, READY, WAITING_FOR_FULL_LOAD, STOPPED_AT_SIGNAL, CRASHED, NEEDS_UPDATING
}
public final double dt;
public final double speed;
public final double acceleration;
public final double s;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof SpeedTimeAndStatus))
return false;
final SpeedTimeAndStatus speedTimeAndStatus = (SpeedTimeAndStatus) o;
if (acceleration != speedTimeAndStatus.acceleration)
return false;
if (dt != speedTimeAndStatus.dt)
return false;
if (s != speedTimeAndStatus.s)
return false;
if (speed != speedTimeAndStatus.speed)
return false;
if (activity != null ? !activity.equals(speedTimeAndStatus.activity)
: speedTimeAndStatus.activity != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
temp = dt != +0.0d ? Double.doubleToLongBits(dt) : 0l;
result = (int) (temp ^ (temp >>> 32));
temp = speed != +0.0d ? Double.doubleToLongBits(speed) : 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
temp = acceleration != +0.0d ? Double.doubleToLongBits(acceleration)
: 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
temp = s != +0.0d ? Double.doubleToLongBits(s) : 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
result = 29 * result + (activity != null ? activity.hashCode() : 0);
return result;
}
private final TrainActivity activity;
SpeedTimeAndStatus(double acceleration, TrainActivity activity, double dt,
double s, double speed) {
if (dt < 0)
throw new IllegalArgumentException(String.valueOf(dt));
this.acceleration = acceleration;
this.activity = activity;
this.dt = dt;
this.s = s;
this.speed = speed;
}
public TrainActivity getActivity() {
return activity;
}
}
Methods:
MethodJavadoc
getActivity
jfreerails.world.train.TrainModel
Javadoc:
/** * Represents a train. * * @author Luke */
Source code:
/**
* Represents a train.
*
* @author Luke
*/
public class TrainModel implements FreerailsSerializable {
public static final int WAGON_LENGTH = 24;
private static final long serialVersionUID = 3545235825756812339L;
public static final int MAX_NUMBER_OF_WAGONS = 6;
public static final int MAX_TRAIN_LENGTH = (1 + MAX_NUMBER_OF_WAGONS)
* WAGON_LENGTH;
private final int scheduleId;
private final int engineTypeId;
private final ImInts wagonTypes;
private final int cargoBundleId;
@Override
public int hashCode() {
int result;
result = scheduleId;
result = 29 * result + engineTypeId;
result = 29 * result + cargoBundleId;
return result;
}
public TrainModel getNewInstance(int newEngine, ImInts newWagons) {
return new TrainModel(newEngine, newWagons, this.getScheduleID(), this
.getCargoBundleID());
}
public TrainModel(int engine, ImInts wagons, int scheduleID, int BundleId) {
engineTypeId = engine;
wagonTypes = wagons;
scheduleId = scheduleID;
cargoBundleId = BundleId;
}
public TrainModel(ImInts wagons, int BundleId) {
wagonTypes = wagons;
cargoBundleId = BundleId;
engineTypeId = 0;
scheduleId = 0;
}
public TrainModel(int engine, ImInts wagons, int scheduleID) {
engineTypeId = engine;
wagonTypes = wagons;
scheduleId = scheduleID;
cargoBundleId = 0;
}
public TrainModel(int engine) {
engineTypeId = engine;
wagonTypes = new ImInts(0, 1, 2);
scheduleId = 0;
cargoBundleId = 0;
}
public int getLength() {
return (1 + wagonTypes.size()) * WAGON_LENGTH; // Engine + wagons.
}
public boolean canAddWagon() {
return wagonTypes.size() < MAX_NUMBER_OF_WAGONS;
}
public int getNumberOfWagons() {
return wagonTypes.size();
}
public int getWagon(int i) {
return wagonTypes.get(i);
}
public int getEngineType() {
return engineTypeId;
}
public int getCargoBundleID() {
return cargoBundleId;
}
public int getScheduleID() {
return scheduleId;
}
public ImInts getConsist() {
return wagonTypes;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof TrainModel) {
TrainModel test = (TrainModel) obj;
boolean b = this.cargoBundleId == test.cargoBundleId
&& this.engineTypeId == test.engineTypeId
&& this.wagonTypes.equals(test.wagonTypes)
&& this.scheduleId == test.scheduleId;
return b;
}
return false;
}
}
Methods:
MethodJavadoc
canAddWagon
getCargoBundleID
getConsist
getEngineType
getLength
getNewInstance
getNumberOfWagons
getScheduleID
getWagon
jfreerails.world.train.TrainMotion
Javadoc:
/** * <p> * This immutable class provides methods that return a train's position and * speed at any time within an interval. An instance of this class will be * stored on the world object for each train rather the train's position. The * reasons for this are as follows. * * <ol type="i"> * <li> It decouples the number of game updates per second and number of frames * per second shown by the client. If the train's position were stored on the * world object, it would get updated each game tick. But this would mean that * if the game was being updated 10 times per second, even if the client was * displaying 50 FPS, the train's motion would still appear jerky since its * position would only change 10 times per second. </li> * <li> * * It makes supporting low bandwidth networks easier since it allows the server * to send updates less frequently. </li> * </p> * * * @author Luke * @see jfreerails.world.train.PathOnTiles * @see jfreerails.world.train.CompositeSpeedAgainstTime */
Source code:
/**
* <p>
* This immutable class provides methods that return a train's position and
* speed at any time within an interval. An instance of this class will be
* stored on the world object for each train rather the train's position. The
* reasons for this are as follows.
*
* <ol type="i">
* <li> It decouples the number of game updates per second and number of frames
* per second shown by the client. If the train's position were stored on the
* world object, it would get updated each game tick. But this would mean that
* if the game was being updated 10 times per second, even if the client was
* displaying 50 FPS, the train's motion would still appear jerky since its
* position would only change 10 times per second. </li>
* <li>
*
* It makes supporting low bandwidth networks easier since it allows the server
* to send updates less frequently. </li>
* </p>
*
*
* @author Luke
* @see jfreerails.world.train.PathOnTiles
* @see jfreerails.world.train.CompositeSpeedAgainstTime
*/
strictfp public class TrainMotion implements Activity<TrainPositionOnMap> {
private static final long serialVersionUID = 3618423722025891641L;
private final double duration, distanceEngineWillTravel;
private final double initialPosition;
private final PathOnTiles path;
private final SpeedAgainstTime speeds;
private final int trainLength;
private final SpeedTimeAndStatus.TrainActivity activity;
/**
* Creates a new TrainMotion instance.
*
* @param path
* the path the train will take.
* @param engineStep
* the position measured in tiles that trains engine is along the
* path
* @param trainLength
* the length of the train, as returned by
* <code>TrainModel.getLength()</code>.
* @throws IllegalArgumentException
* if trainLength is out the range
* <code>trainLength &gt; TrainModel.WAGON_LENGTH || trainLength &lt; TrainModel.MAX_TRAIN_LENGTH</code>
* @throws IllegalArgumentException
* if
* <code>path.getDistance(engineStep) &lt; trainLength</code>.
* @throws IllegalArgumentException
* if
* <code>(path.getLength() - initialPosition) &gt; speeds.getTotalDistance()</code>.
*/
public TrainMotion(PathOnTiles path, int engineStep, int trainLength,
SpeedAgainstTime speeds) {
if (trainLength < TrainModel.WAGON_LENGTH
|| trainLength > TrainModel.MAX_TRAIN_LENGTH)
throw new IllegalArgumentException();
this.path = path;
this.speeds = speeds;
this.trainLength = trainLength;
if(engineStep > path.steps())
throw new ArrayIndexOutOfBoundsException(String.valueOf(engineStep));
initialPosition = path.getDistance(engineStep);
if (initialPosition < trainLength)
throw new IllegalArgumentException(
"The engine's initial position is not far enough along the path for "
+ "the train's initial position to be specified.");
double totalPathDistance = path.getTotalDistance();
distanceEngineWillTravel = totalPathDistance - initialPosition;
if (distanceEngineWillTravel > speeds.getS())
throw new IllegalArgumentException(
"The train's speed is not defined for the whole of the journey.");
if(distanceEngineWillTravel == 0){
duration = 0d;
}else{
double tempDuration = speeds.calcT(distanceEngineWillTravel);
while((speeds.calcS(tempDuration) - distanceEngineWillTravel) > 0){
tempDuration -= Math.ulp(tempDuration);
}
duration = tempDuration;
}
activity = SpeedTimeAndStatus.TrainActivity.READY;
sanityCheck();
}
/** Checks we are not creating an object with an inconsistent state. That is, at the
* time stored in the field duration, the engine must not have gone off the end of the path.*/
private void sanityCheck() {
double offset = calcOffSet(duration);
double totalLength = path.getTotalDistance();
double trainLengthDouble = trainLength;
if(totalLength < offset + trainLengthDouble)
throw new IllegalStateException(offset +" + "+ trainLengthDouble+" > " +totalLength);
}
public TrainMotion(PathOnTiles path, int trainLength, double duration, SpeedTimeAndStatus.TrainActivity act){
this.path = path;
this.trainLength = trainLength;
this.activity = act;
this.distanceEngineWillTravel = 0;
this.initialPosition = path.getTotalDistance();
this.speeds = ConstAcc.STOPPED;
this.duration = duration;
}
private double calcOffSet(double t) {
double offset = getDistance(t) + initialPosition - trainLength;
return offset;
}
void checkT(double t) {
if (t < 0d || t > duration)
throw new IllegalArgumentException("t=" + t + ", but duration="
+ duration);
}
public double duration() {
return duration;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TrainMotion))
return false;
final TrainMotion trainMotion = (TrainMotion) o;
if (trainLength != trainMotion.trainLength)
return false;
if (!path.equals(trainMotion.path))
return false;
if (!speeds.equals(trainMotion.speeds))
return false;
return true;
}
/**
* Returns the train's distance along the track from the point the train was
* at at time <code>getStart()</code> at the specified time.
*
* @param t
* the time.
* @return the distance
* @throws IllegalArgumentException
* if t is outside the interval
*/
public double getDistance(double t) {
checkT(t);
t = Math.min(t, speeds.getT());
return speeds.calcS(t);
}
public PositionOnTrack getFinalPosition() {
return path.getFinalPosition();
}
public double getSpeedAtEnd() {
double finalT = speeds.getT();
return speeds.calcV(finalT);
}
/**
* Returns the train's position at the specified time.
*
* @param t
* the time.
* @return the train's position.
* @throws IllegalArgumentException
* if t is outside the interval
*/
public TrainPositionOnMap getState(double t) {
t = Math.min(t, speeds.getT());
double offset = calcOffSet(t);
FreerailsPathIterator pathIt = path.subPath(offset, trainLength);
double speed = speeds.calcV(t);
double acceleration = speeds.calcA(t);
TrainPositionOnMap tpom = TrainPositionOnMap
.createInSameDirectionAsPath(pathIt, speed, acceleration,
activity);
return tpom.reverse();
}
/**
* Returns a PathOnTiles object that identifies the tiles the train is on at
* the specified time.
*
* @param t
* the time.
* @return an array of the tiles the train is on
* @throws IllegalArgumentException
* if t is outside the interval
*/
public PathOnTiles getTiles(double t) {
checkT(t);
t = Math.min(t, speeds.getT());
double start = calcOffSet(t);
double end = start + trainLength;
ArrayList<Step> steps = new ArrayList<Step>();
double distanceSoFar = 0;
int stepsBeforeStart = 0;
int stepsAfterEnd = 0;
for (int i = 0; i < path.steps(); i++) {
if (distanceSoFar > end)
stepsAfterEnd++;
Step step = path.getStep(i);
distanceSoFar += step.getLength();
if (distanceSoFar < start)
stepsBeforeStart++;
}
if (distanceSoFar < start) {
// throw new IllegalStateException();
}
if (distanceSoFar < (end - 0.1)) {
// throw new IllegalStateException();
}
int lastStep = path.steps() - stepsAfterEnd;
for (int i = stepsBeforeStart; i < lastStep; i++) {
steps.add(path.getStep(i));
}
ImPoint p = path.getStart();
int x = p.x;
int y = p.y;
for (int i = 0; i < stepsBeforeStart; i++) {
Step step = path.getStep(i);
x += step.deltaX;
y += step.deltaY;
}
ImPoint startPoint = new ImPoint(x, y);
PathOnTiles pathOnTiles = new PathOnTiles(startPoint, steps);
return pathOnTiles;
}
public int getTrainLength() {
return trainLength;
}
@Override
public int hashCode() {
int result;
result = path.hashCode();
result = 29 * result + speeds.hashCode();
result = 29 * result + trainLength;
return result;
}
public PathOnTiles getPath() {
return path;
}
public SpeedTimeAndStatus.TrainActivity getActivity() {
return activity;
}
public double getInitialPosition() {
return initialPosition;
}
}
Methods:
MethodJavadoc
calcOffSet
checkT
duration
getActivity
getDistance/**
getFinalPosition
getInitialPosition
getPath/**
getSpeedAtEnd
getState/**
getTiles/**
getTrainLength
sanityCheck/** Checks we are not creating an object with an inconsistent state. That is, at the
jfreerails.world.train.TrainOrdersModel
Javadoc:
/** * This class encapsulates the orders for a train. * * @author Luke */
Source code:
/**
* This class encapsulates the orders for a train.
*
* @author Luke
*/
public class TrainOrdersModel implements FreerailsSerializable {
private static final long serialVersionUID = 3616453397155559472L;
private static final int MAXIMUM_NUMBER_OF_WAGONS = 6;
public final boolean waitUntilFull;
public final boolean autoConsist;
/** The wagon types to add; if null, then no change.*/
public final ImInts consist;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TrainOrdersModel))
return false;
final TrainOrdersModel trainOrdersModel = (TrainOrdersModel) o;
if (autoConsist != trainOrdersModel.autoConsist)
return false;
if (stationId != trainOrdersModel.stationId)
return false;
if (waitUntilFull != trainOrdersModel.waitUntilFull)
return false;
if (consist != null ? !consist.equals(trainOrdersModel.consist)
: trainOrdersModel.consist != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = (waitUntilFull ? 1 : 0);
result = 29 * result + (autoConsist ? 1 : 0);
result = 29 * result + (consist != null ? consist.hashCode() : 0);
result = 29 * result + stationId;
return result;
}
public final int stationId; // The number of the station to goto.
public TrainOrdersModel(int station, ImInts newConsist, boolean wait,
boolean auto) {
// If there are no wagons, set wait = false.
wait = (null == newConsist || 0 == newConsist.size()) ? false : wait;
this.waitUntilFull = wait;
this.consist = newConsist;
this.stationId = station;
this.autoConsist = auto;
}
/**
* @return either (1) an array of cargo type ids or (2) null to represent
* 'no change'.
*/
public ImInts getConsist() {
return this.consist;
}
public int getStationID() {
return stationId;
}
public boolean isNoConsistChange() {
return null == consist;
}
public boolean getWaitUntilFull() {
return waitUntilFull;
}
public boolean orderHasWagons() {
return null != consist && 0 != consist.size();
}
public boolean hasLessThanMaximumNumberOfWagons() {
return null == consist || consist.size() < MAXIMUM_NUMBER_OF_WAGONS;
}
public boolean isAutoConsist() {
return autoConsist;
}
}
Methods:
MethodJavadoc
getConsist/**
getStationID
getWaitUntilFull
hasLessThanMaximumNumberOfWagons
isAutoConsist
isNoConsistChange
orderHasWagons
jfreerails.world.train.TrainPathIterator
Javadoc:
/** * Exposes the path of a train. TODO needs better comment * * @author Luke Lindsay * */
Source code:
/**
* Exposes the path of a train. TODO needs better comment
*
* @author Luke Lindsay
*
*/
public class TrainPathIterator implements FreerailsPathIterator {
private static final long serialVersionUID = 3256999977816502584L;
private final FreerailsIntIterator intIterator;
private final PositionOnTrack p1 = new PositionOnTrack();
private final PositionOnTrack p2 = new PositionOnTrack();
private static final int tileSize = Constants.TILE_SIZE;
public TrainPathIterator(FreerailsIntIterator i) {
intIterator = i;
p2.setValuesFromInt(intIterator.nextInt());
}
public boolean hasNext() {
return intIterator.hasNextInt();
}
public void nextSegment(IntLine line) {
p1.setValuesFromInt(p2.toInt());
line.x1 = p1.getX() * tileSize + tileSize / 2;
line.y1 = p1.getY() * tileSize + tileSize / 2;
p2.setValuesFromInt(intIterator.nextInt());
line.x2 = p2.getX() * tileSize + tileSize / 2;
line.y2 = p2.getY() * tileSize + tileSize / 2;
}
}
Methods:
MethodJavadoc
hasNext
nextSegment
jfreerails.world.train.TrainPositionOnMap
Javadoc:
/** * This <b>immutable</b> class represents the position of a train as a String * of points. There must be at least two points. The first point is the position * of the front of the train; the last point is the position of the end of the * train. Any intermediate points are positions of 'kinks' in the track. * * Coordinates are expressed in display coordinates relative to the map origin * (as opposed to map squares). * * * <p> * Train positions can be combined and divided as illustrated below (notice what * happens to the head and tail that are combined) * </p> * <table width="100%" border="0"> * <tr> * <td>if</td> * <td><code> a</code></td> * <td><code>=</code></td> * <td><code>{<strong>(10, 10)</strong>, (20,20), (30,30), (40,40) }</code></td> * </tr> * <tr> * <td>and</td> * <td><code> b</code></td> * <td><code>=</code></td> * <td><code>{(1,1), (4,4), (5,5), <strong>(10, 10)</strong>}</code></td> * </tr> * <tr> * <td>then</td> * <td><code>a.addToHead(b)</code></td> * <td><code>=</code></td> * <td><code>{(1,1), (4,4), (5,5), (20,20), (30,30), (40,40) }</code></td> * </tr> * <tr> * <td>and</td> * <td><code>b.addToTail(a)</code></td> * <td><code>=</code></td> * <td><code>{(1,1), (4,4), (5,5), (20,20), (30,30), (40,40) }</code></td> * </tr> * <tr> * <td>and if</td> * <td><code> c</code></td> * <td><code>=</code></td> * <td><code>{(1,1), (4,4), (5,5), (20,20), (30,30), (40,40) }</code></td> * </tr> * <tr> * <td>then</td> * <td><code>c.removeFromTail(a)</code></td> * <td><code>=</code></td> * <td><code>{(1,1), (4,4), (5,5), (10, 10)}</code></td> * </tr> * <tr> * <td>and</td> * <td><code>c.removeFromHead(b)</code></td> * <td><code>=</code></td> * <td><code>{(10, 10), (20,20), (30,30), (40,40) }</code></td> * </tr> * </table> * * * @author Luke Lindsay 26-Oct-2002 * */
Source code:
/**
* This <b>immutable</b> class represents the position of a train as a String
* of points. There must be at least two points. The first point is the position
* of the front of the train; the last point is the position of the end of the
* train. Any intermediate points are positions of 'kinks' in the track.
*
* Coordinates are expressed in display coordinates relative to the map origin
* (as opposed to map squares).
*
*
* <p>
* Train positions can be combined and divided as illustrated below (notice what
* happens to the head and tail that are combined)
* </p>
* <table width="100%" border="0">
* <tr>
* <td>if</td>
* <td><code> a</code></td>
* <td><code>=</code></td>
* <td><code>{<strong>(10, 10)</strong>, (20,20), (30,30), (40,40) }</code></td>
* </tr>
* <tr>
* <td>and</td>
* <td><code> b</code></td>
* <td><code>=</code></td>
* <td><code>{(1,1), (4,4), (5,5), <strong>(10, 10)</strong>}</code></td>
* </tr>
* <tr>
* <td>then</td>
* <td><code>a.addToHead(b)</code></td>
* <td><code>=</code></td>
* <td><code>{(1,1), (4,4), (5,5), (20,20), (30,30), (40,40) }</code></td>
* </tr>
* <tr>
* <td>and</td>
* <td><code>b.addToTail(a)</code></td>
* <td><code>=</code></td>
* <td><code>{(1,1), (4,4), (5,5), (20,20), (30,30), (40,40) }</code></td>
* </tr>
* <tr>
* <td>and if</td>
* <td><code> c</code></td>
* <td><code>=</code></td>
* <td><code>{(1,1), (4,4), (5,5), (20,20), (30,30), (40,40) }</code></td>
* </tr>
* <tr>
* <td>then</td>
* <td><code>c.removeFromTail(a)</code></td>
* <td><code>=</code></td>
* <td><code>{(1,1), (4,4), (5,5), (10, 10)}</code></td>
* </tr>
* <tr>
* <td>and</td>
* <td><code>c.removeFromHead(b)</code></td>
* <td><code>=</code></td>
* <td><code>{(10, 10), (20,20), (30,30), (40,40) }</code></td>
* </tr>
* </table>
*
*
* @author Luke Lindsay 26-Oct-2002
*
*/
public class TrainPositionOnMap implements FreerailsSerializable {
public static final int CRASH_FRAMES_COUNT = 15;
private static final long serialVersionUID = 3979269144611010865L;
private final ImInts xpoints;
private final ImInts ypoints;
private final double speed, acceleration;
private final SpeedTimeAndStatus.TrainActivity activity;
private boolean crashSite = false;
public boolean isCrashSite() {
return crashSite;
}
public void setCrashSite(boolean isCrash) {
crashSite = isCrash;
}
private int frameCt = 1;
private int frame = 0;
public int getFrameCt() {
return frameCt;
}
public void incrementFramCt() {
if (frame > 0) {
incrementFrame();
frame = 0;
} else {
frame++;
}
}
public void incrementFrame() {
frameCt++;
}
@Override
public int hashCode() {
int result = 0;
// TODO is there are danger of overflow here?
for (int i = 0; i < xpoints.size(); i++) {
result = 29 * result + xpoints.get(i);
}
for (int i = 0; i < ypoints.size(); i++) {
result = 29 * result + ypoints.get(i);
}
return result;
}
@Override
public boolean equals(Object o) {
if (null == o) {
return false;
}
if (o == this) {
return true;
}
if (o instanceof TrainPositionOnMap) {
TrainPositionOnMap other = (TrainPositionOnMap) o;
int thisLength = this.getLength();
int otherLength = other.getLength();
if (thisLength == otherLength) {
FreerailsPathIterator path1;
FreerailsPathIterator path2;
IntLine line1 = new IntLine();
IntLine line2 = new IntLine();
path1 = other.path();
path2 = this.path();
while (path1.hasNext() && path2.hasNext()) {
path1.nextSegment(line1);
path2.nextSegment(line2);
if (line1.x1 != line2.x1 || line1.y1 != line2.y1
|| line1.x2 != line2.x2 || line1.y2 != line2.y2) {
return false;
}
}
if (path1.hasNext() || path2.hasNext()) {
return false;
}
return true;
}
return false;
}
return false;
}
public double calculateDistance() {
double distance = 0;
IntLine line = new IntLine();
FreerailsPathIterator path = this.path();
while (path.hasNext()) {
path.nextSegment(line);
int sumOfSquares = (line.x1 - line.x2) * (line.x1 - line.x2)
+ (line.y1 - line.y2) * (line.y1 - line.y2);
distance += Math.sqrt(sumOfSquares);
}
return distance;
}
public int getLength() {
return xpoints.size();
}
public ImInts getXPoints() {
return xpoints;
}
public ImInts getYPoints() {
return ypoints;
}
public int getX(int position) {
return xpoints.get(position);
}
public int getY(int position) {
return ypoints.get(position);
}
public FreerailsPathIterator path() {
return new SimplePathIteratorImpl(this.xpoints, this.ypoints);
}
public FreerailsPathIterator reversePath() {
int length = xpoints.size();
int[] reversed_xpoints = new int[length];
int[] reversed_ypoints = new int[length];
for (int i = 0; i < length; i++) {
reversed_xpoints[i] = xpoints.get(length - i - 1);
reversed_ypoints[i] = ypoints.get(length - i - 1);
}
return new SimplePathIteratorImpl(reversed_xpoints, reversed_ypoints);
}
public TrainPositionOnMap reverse() {
int length = xpoints.size();
int[] reversed_xpoints = new int[length];
int[] reversed_ypoints = new int[length];
for (int i = 0; i < length; i++) {
reversed_xpoints[i] = xpoints.get(length - i - 1);
reversed_ypoints[i] = ypoints.get(length - i - 1);
}
return new TrainPositionOnMap(reversed_xpoints, reversed_ypoints,
speed, acceleration, activity);
}
public TrainPositionOnMap(ImInts xs, ImInts ys) {
this.xpoints = xs;
this.ypoints = ys;
this.acceleration = 0d;
this.speed = 0d;
this.activity = SpeedTimeAndStatus.TrainActivity.READY;
}
private TrainPositionOnMap(int[] xs, int[] ys, double speed,
double acceleration, SpeedTimeAndStatus.TrainActivity activity) {
if (xs.length != ys.length) {
throw new IllegalArgumentException();
}
xpoints = new ImInts(xs);
ypoints = new ImInts(ys);
this.acceleration = acceleration;
this.speed = speed;
this.activity = activity;
}
public static TrainPositionOnMap createInstance(int[] xpoints, int[] ypoints) {
return new TrainPositionOnMap(xpoints, ypoints, 0d, 0d,
SpeedTimeAndStatus.TrainActivity.READY);
}
public TrainPositionOnMap addToHead(TrainPositionOnMap b) {
TrainPositionOnMap a = this;
return addBtoHeadOfA(b, a);
}
private TrainPositionOnMap addBtoHeadOfA(TrainPositionOnMap b,
TrainPositionOnMap a) {
if (aHeadEqualsBTail(a, b)) {
int newLength = a.getLength() + b.getLength() - 2;
int[] newXpoints = new int[newLength];
int[] newYpoints = new int[newLength];
int aLength = a.getLength();
int bLength = b.getLength();
// First copy the points from B
for (int i = 0; i < bLength - 1; i++) {
newXpoints[i] = b.getX(i);
newYpoints[i] = b.getY(i);
}
// Second copy the points from A.
for (int i = 1; i < aLength; i++) {
newXpoints[i + bLength - 2] = a.getX(i);
newYpoints[i + bLength - 2] = a.getY(i);
}
return new TrainPositionOnMap(newXpoints, newYpoints,
b.acceleration, b.speed, b.activity);
}
throw new IllegalArgumentException("Tried to add " + b.toString()
+ " to the head of " + a.toString());
}
public boolean canAddToHead(TrainPositionOnMap b) {
return aHeadEqualsBTail(this, b);
}
public TrainPositionOnMap addToTail(TrainPositionOnMap a) {
TrainPositionOnMap b = this;
return addBtoHeadOfA(b, a);
}
public boolean canAddToTail(TrainPositionOnMap b) {
return aHeadEqualsBTail(b, this);
}
public TrainPositionOnMap removeFromHead(TrainPositionOnMap b) {
if (headsAreEqual(this, b)) {
int newLength = this.getLength() - b.getLength() + 2;
int[] newXpoints = new int[newLength];
int[] newYpoints = new int[newLength];
int bLength = b.getLength();
// copy head from b
int bHeadPosition = b.getLength() - 1;
newXpoints[0] = b.getX(bHeadPosition);
newYpoints[0] = b.getY(bHeadPosition);
// Copy rest from this
for (int i = 1; i < newLength; i++) {
int position = bLength + i - 2;
newXpoints[i] = this.getX(position);
newYpoints[i] = this.getY(position);
}
return new TrainPositionOnMap(newXpoints, newYpoints, speed,
acceleration, activity);
}
throw new IllegalArgumentException();
}
public boolean canRemoveFromHead(TrainPositionOnMap b) {
if (headsAreEqual(this, b)) {
FreerailsPathIterator path = b.path();
int i = 0;
IntLine line = new IntLine();
while (path.hasNext()) {
path.nextSegment(line);
if (this.getX(i) != line.x1 || this.getY(i) != line.y1) {
return false;
}
i++;
}
return true;
}
return false;
}
public TrainPositionOnMap removeFromTail(TrainPositionOnMap b) {
if (tailsAreEqual(this, b)) {
int newLength = this.getLength() - b.getLength() + 2;
int[] newXpoints = new int[newLength];
int[] newYpoints = new int[newLength];
// Copy from this
for (int i = 0; i < newLength - 1; i++) {
newXpoints[i] = this.getX(i);
newYpoints[i] = this.getY(i);
}
// Copy tail from b
newXpoints[newLength - 1] = b.getX(0);
newYpoints[newLength - 1] = b.getY(0);
return new TrainPositionOnMap(newXpoints, newYpoints, speed,
acceleration, activity);
}
throw new IllegalArgumentException();
}
public boolean canRemoveFromTail(TrainPositionOnMap b) {
if (tailsAreEqual(this, b)) {
FreerailsPathIterator path = b.reversePath();
int i = this.getLength() - 1;
IntLine line = new IntLine();
while (path.hasNext()) {
path.nextSegment(line);
if (this.getX(i) != line.x1 || this.getY(i) != line.y1) {
return false;
}
i--;
}
return true;
}
return false;
}
public static TrainPositionOnMap createInSameDirectionAsPath(
FreerailsPathIterator path) {
return createInSameDirectionAsPath(path, 0d, 0d,
SpeedTimeAndStatus.TrainActivity.READY);
}
public static TrainPositionOnMap createInSameDirectionAsPath(
FreerailsPathIterator path, double speed, double acceleration,
SpeedTimeAndStatus.TrainActivity activity) {
IntArray xPointsIntArray = new IntArray();
IntArray yPointsIntArray = new IntArray();
IntLine line = new IntLine();
int i = 0;
while (path.hasNext()) {
path.nextSegment(line);
xPointsIntArray.add(i, line.x1);
yPointsIntArray.add(i, line.y1);
i++;
if (i > 10000) {
throw new IllegalStateException(
"The TrainPosition has more than 10,000 points, which suggests that something is wrong.");
}
}
xPointsIntArray.add(i, line.x2);
yPointsIntArray.add(i, line.y2);
int[] xPoints;
int[] yPoints;
xPoints = xPointsIntArray.toArray();
yPoints = yPointsIntArray.toArray();
return new TrainPositionOnMap(xPoints, yPoints, speed, acceleration,
activity);
}
public static boolean headsAreEqual(TrainPositionOnMap a,
TrainPositionOnMap b) {
int aHeadX = a.getX(0);
int aHeadY = a.getY(0);
int bHeadX = b.getX(0);
int bHeadY = b.getY(0);
if (aHeadX == bHeadX && aHeadY == bHeadY) {
return true;
}
return false;
}
public static boolean tailsAreEqual(TrainPositionOnMap a,
TrainPositionOnMap b) {
int aTailX = a.getX(a.getLength() - 1);
int aTailY = a.getY(a.getLength() - 1);
int bTailX = b.getX(b.getLength() - 1);
int bTailY = b.getY(b.getLength() - 1);
if (aTailX == bTailX && aTailY == bTailY) {
return true;
}
return false;
}
public static boolean aHeadEqualsBTail(TrainPositionOnMap a,
TrainPositionOnMap b) {
int aHeadX = a.getX(0);
int aHeadY = a.getY(0);
int bTailX = b.getX(b.getLength() - 1);
int bTailY = b.getY(b.getLength() - 1);
if (aHeadX == bTailX && aHeadY == bTailY) {
return true;
}
return false;
}
public static boolean bHeadEqualsATail(TrainPositionOnMap a,
TrainPositionOnMap b) {
return aHeadEqualsBTail(b, a);
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("TrainPosition {");
for (int i = 0; i < xpoints.size(); i++) {
sb.append("(");
sb.append(xpoints.get(i));
sb.append(", ");
sb.append(ypoints.get(i));
sb.append("), ");
}
sb.append("}");
return sb.toString();
}
public double getAcceleration() {
return acceleration;
}
public SpeedTimeAndStatus.TrainActivity getActivity() {
return activity;
}
public double getSpeed() {
return speed;
}
}
Methods:
MethodJavadoc
aHeadEqualsBTail
addBtoHeadOfA
addToHead/**
addToTail
bHeadEqualsATail
calculateDistance
canAddToHead
canAddToTail
canRemoveFromHead
canRemoveFromTail
createInSameDirectionAsPath
createInSameDirectionAsPath
createInstance
getAcceleration
getActivity
getFrameCt
getLength
getSpeed
getX
getXPoints
getY
getYPoints
headsAreEqual
incrementFramCt
incrementFrame
isCrashSite
path
removeFromHead
removeFromTail
reverse/**
reversePath
setCrashSite
tailsAreEqual
jfreerails.world.train.WagonType
Javadoc:
/** * This class represents a wagon type, for example 'goods wagon'. It * encapsulates the properties of a wagon that are common to all wagons of the * same type. * * @author Luke * */
Source code:
/**
* This class represents a wagon type, for example 'goods wagon'. It
* encapsulates the properties of a wagon that are common to all wagons of the
* same type.
*
* @author Luke
*
*/
public class WagonType implements FreerailsSerializable {
private static final long serialVersionUID = 3906368233710826292L;
public static final int BULK_FREIGHT = 4;
public static final int ENGINE = 5;
public static final int FAST_FREIGHT = 2;
public static final int MAIL = 0;
public static final int NUMBER_OF_CATEGORIES = 6;
public static final int PASSENGER = 1;
public static final int SLOW_FREIGHT = 3;
public static final int UNITS_OF_CARGO_PER_WAGON = 40;
private final int typeCategory;
private final String typeName;
public WagonType(String name, int category) {
typeName = name;
typeCategory = category;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof WagonType))
return false;
WagonType other = (WagonType) obj;
return other.typeCategory == this.typeCategory
&& other.typeName.equals(typeName);
}
public int getCategory() {
return typeCategory;
}
public String getName() {
return typeName;
}
@Override
public int hashCode() {
int result;
result = typeCategory;
result = 29 * result + typeName.hashCode();
return result;
}
@Override
public String toString() {
return typeName;
}
}
Methods:
MethodJavadoc
getCategory
getName

Methods Details

experimental.AnimationExpt.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
System.setProperty("SHOWFPS", "true");
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.getContentPane().add(new AnimationExpt());
ScreenHandler screenHandler = new ScreenHandler(f,
ScreenHandler.WINDOWED_MODE);
screenHandler.apply();
GameLoop gameLoop = new GameLoop(screenHandler);
Thread t = new Thread(gameLoop);
t.start();
}
Outgoing Methods (calls):
experimental.AnimationExpt.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
long l = System.currentTimeMillis();
String str = String.valueOf(l);
g.drawString(str, 100, 100);
}
No outgoing methods.
experimental.CheckFreerailsSerializableClasses.checkFields
Javadoc:
No Javadoc available
Method code:
static boolean checkFields(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
boolean okSoFar = true;
boolean assertImmutable = clazz.isAnnotationPresent(Immutable.class);
for (Field field : fields) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers)) {
logger.fine("Skipping static field " + field.getName());
continue;
}
Class<?> type = field.getType();
if (type.isPrimitive()) {
continue;
}
// if(!Modifier.isPrivate(modifiers)){
// System.err.println(clazz.getName()+field.getName()+" should be
// private!");
// okSoFar = false;
// }
if (!FreerailsSerializable.class.isAssignableFrom(type)
&& !assertImmutable) {
if (!immutableTypes.contains(type) && !type.isEnum()
&& !type.isAnnotationPresent(Immutable.class)) {
System.err.println(clazz.getName() + "." + field.getName()
+ " {" + type.getName()
+ "} might not be immutable!");
okSoFar = false;
if (!type.isArray())
mutableTypes.add(type);
}
}
}
return okSoFar;
}
No outgoing methods.
experimental.CheckFreerailsSerializableClasses.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
immutableTypes.clear();
mutableTypes.clear();
immutableTypes.add(String.class);
// Class clazz = StationModel.class;
// System.err.println(overridesHashCodeAndEquals(clazz));
// System.out.println(clazz.isAnnotationPresent(InstanceControlled.class));
// Annotation[] ans = clazz.getAnnotations();
// for (Annotation an : ans) {
// System.err.println(an);
// }
// System.err.println(checkFields(clazz));
testAllClasses();
for (Class c : mutableTypes) {
System.err.println(c.getName());
}
}
Outgoing Methods (calls):
experimental.CheckFreerailsSerializableClasses.overridesHashCodeAndEquals
Javadoc:
No Javadoc available
Method code:
static boolean overridesHashCodeAndEquals(Class clazz) {
try {
boolean okSoFar = true;
Method equals = clazz.getMethod("equals", Object.class);
if (equals.getDeclaringClass().equals(Object.class)) {
System.err.println(clazz.getName() + " does not override "
+ equals.getName());
okSoFar = false;
}
Method hashCode = clazz.getMethod("hashCode");
if (hashCode.getDeclaringClass().equals(Object.class)) {
System.err.println(clazz.getName() + " does not override "
+ hashCode.getName());
okSoFar = false;
}
return okSoFar;
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
No outgoing methods.
experimental.CheckFreerailsSerializableClasses.testAllClasses
Javadoc:
No Javadoc available
Method code:
@SuppressWarnings("unchecked")
static void testAllClasses() {
ClassLocater locater = new ClassLocater();
Class[] classes = locater.getSubclassesOf(FreerailsSerializable.class);
int classesWithProblems = 0;
for (Class clazz : classes) {
if (clazz.isInterface()) {
logger.fine("Skipping interface " + clazz.getName());
continue;
}
int mods = clazz.getModifiers();
if ((mods & Modifier.ABSTRACT) != 0) {
logger.fine("Skipping abstract class " + clazz.getName());
continue;
}
if (clazz.isAnnotationPresent(InstanceControlled.class)) {
logger.fine("Skipping InstanceControlled class "
+ clazz.getName());
continue;
}
boolean b = overridesHashCodeAndEquals(clazz);
b = b && checkFields(clazz);
if (!b) {
classesWithProblems++;
}
}
System.err.println(classes.length + " classes checked, "
+ classesWithProblems + " have problems");
}
Outgoing Methods (calls):
experimental.ConnectAllCities.main
Javadoc:
/** * @param args the command line arguments */
Method code:
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException, PathNotFoundException {
SavedGamesManager gamesManager = new SavedGamesManagerImpl();
String[] newMapNames = gamesManager.getNewMapNames();
World w = (World) gamesManager.newMap(newMapNames[0]);
System.out.println(w.getClass());
ServerGameModel gameModel = new ServerGameModelImpl();
String name = "Tester";
Player p = new Player(name, 0);
Move addPlayerMove = AddPlayerMove.generateMove(w, p);
MoveStatus ms = addPlayerMove.doMove(w, Player.AUTHORITATIVE);
w.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
w.setTime(new GameTime(0));
w.set(ITEM.GAME_SPEED, new GameSpeed(10));
w.set(ITEM.GAME_RULES, GameRules.DEFAULT_RULES);
Transaction t = new AddItemTransaction(Transaction.Category.BOND, 0, 1, new Money(50000000));
w.addTransaction(p.getPrincipal(), t);
List<CityModel> citiesUnconnected = new ArrayList<>();
List<CityModel> citiesConnected = new ArrayList<>();
int nCities = w.size(SKEY.CITIES);
System.out.format("There are %d cities.%n", nCities);
for (int i = 0; i < nCities; i++) {
citiesUnconnected.add((CityModel) w.get(SKEY.CITIES, i));
}
CityModel cityA = citiesUnconnected.remove(0);
citiesConnected.add(cityA);
DistanceComparator distanceComparator = new DistanceComparator(cityA.getCityX(), cityA.getCityY());
Collections.sort(citiesUnconnected, distanceComparator);
MapCustomizer mc = new MapCustomizer(w);
int n = citiesUnconnected.size();
for (int i = 0; i < n; i++) {
CityModel cityB = citiesUnconnected.remove(0);
System.out.format("build track to %s%n", cityB.getCityName());
distanceComparator = new DistanceComparator(cityB.getCityX(), cityB.getCityY());
Collections.sort(citiesConnected, distanceComparator);
ImPoint b = cityB.getLocation();
for (int j = 0; j < Math.min(3, citiesConnected.size()); j++) {
cityA = citiesConnected.get(j);
ImPoint a = cityA.getLocation();
mc.buildTrack(a, b);
try {
if (j == 0) {
if (i == 0) {
mc.buildStation(a);
}
mc.buildStation(b);
}
} catch (java.lang.IllegalStateException e) {
//sometimes it is not possible to build the
//stations, e.g. another one is too close.
break;
}
int stationA = mc.getStationId(a);
int stationB = mc.getStationId(b);
if (stationA >= 0 && stationB >= 0) {
//the stations exist.
mc.buildTrain(b, stationA, stationB);
}
}
System.out.format("There are %d stations%n", w.size(p.getPrincipal(), KEY.STATIONS));
citiesConnected.add(cityB);
}
System.out.println(ms);
String[] passwords = {"password"};
gameModel.setWorld(w, passwords);
gamesManager.saveGame(gameModel, "generated.sav");
}
Outgoing Methods (calls):
experimental.DialogueBoxTester.exitForm
Javadoc:
/** Exit the Application. */
Method code:
/** Exit the Application. */
private void exitForm(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_exitForm
System.exit(0);
}// GEN-LAST:event_exitForm
No outgoing methods.
experimental.DialogueBoxTester.formKeyPressed
Javadoc:
No Javadoc available
Method code:
private void formKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_formKeyPressed
if (java.awt.event.KeyEvent.VK_ESCAPE == evt.getKeyCode()) {
dialogueBoxController.closeContent();
}
}// GEN-LAST:event_formKeyPressed
Outgoing Methods (calls):
experimental.DialogueBoxTester.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the FormEditor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
jLabel1 = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
show = new javax.swing.JMenu();
showBrokerScreen = new javax.swing.JMenuItem();
selectEngine = new javax.swing.JMenuItem();
selectWagons = new javax.swing.JMenuItem();
selectTrainOrders = new javax.swing.JMenuItem();
showControls = new javax.swing.JMenuItem();
showTerrainInfo = new javax.swing.JMenuItem();
showStationInfo = new javax.swing.JMenuItem();
showTrainList = new javax.swing.JMenuItem();
showReportBug = new javax.swing.JMenuItem();
throwException = new javax.swing.JMenuItem();
showCargoWaitingAndDemand = new javax.swing.JMenuItem();
showJavaSystemProperties = new javax.swing.JMenuItem();
showNetworthGraph = new javax.swing.JMenuItem();
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/jfreerails/data/south_america.png")));
jLabel1.setText("Press Esc to close dialogue boxes");
jLabel1.setMinimumSize(new java.awt.Dimension(640, 480));
jLabel1.setPreferredSize(new java.awt.Dimension(640, 480));
getContentPane().add(jLabel1, java.awt.BorderLayout.CENTER);
show.setText("Show");
showBrokerScreen.setText("Broker Screen");
showBrokerScreen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newspaperActionPerformed(evt);
}
});
show.add(showBrokerScreen);
selectEngine.setText("Select Engine");
selectEngine.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectEngineActionPerformed(evt);
}
});
show.add(selectEngine);
selectWagons.setText("Select Wagons");
selectWagons.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectWagonsActionPerformed(evt);
}
});
show.add(selectWagons);
selectTrainOrders.setText("Train Orders");
selectTrainOrders
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectTrainOrdersActionPerformed(evt);
}
});
show.add(selectTrainOrders);
showControls.setText("Show game controls");
showControls.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showControlsActionPerformed(evt);
}
});
show.add(showControls);
showTerrainInfo.setText("Show Terrain Info");
showTerrainInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showTerrainInfoActionPerformed(evt);
}
});
show.add(showTerrainInfo);
showStationInfo.setText("Show Station Info");
showStationInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showStationInfoActionPerformed(evt);
}
});
show.add(showStationInfo);
showTrainList.setText("Train List");
showTrainList.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showTrainListActionPerformed(evt);
}
});
show.add(showTrainList);
showCargoWaitingAndDemand.setText("Cargo waiting & demand");
showCargoWaitingAndDemand
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showCargoWaitingAndDemandActionPerformed(evt);
}
});
show.add(showCargoWaitingAndDemand);
showJavaSystemProperties.setText("Java System Properties");
showJavaSystemProperties
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showJavaSystemPropertiesActionPerformed(evt);
}
});
throwException.setText("Throw Exception");
throwException.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
throw new IllegalArgumentException();
}
});
show.add(showJavaSystemProperties);
showNetworthGraph.setText("Show networth graph");
showNetworthGraph
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showNetworthGraphActionPerformed(evt);
}
});
show.add(showNetworthGraph);
showReportBug.setText("Report Bug");
showReportBug
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showReportBug();
}
});
show.add(showReportBug);
jMenuBar1.add(show);
setJMenuBar(jMenuBar1);
}// GEN-END:initComponents
Outgoing Methods (calls):
experimental.DialogueBoxTester.main
Javadoc:
No Javadoc available
Method code:
public static void main(String args[]) {
DialogueBoxTester test = new DialogueBoxTester();
test.setVisible(true);
}
No outgoing methods.
experimental.DialogueBoxTester.newspaperActionPerformed
Javadoc:
No Javadoc available
Method code:
private void newspaperActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_newspaperActionPerformed
// Add your handling code here:
dialogueBoxController.showBrokerScreen();
//dialogueBoxController.showNewspaper("New headline!");
}// GEN-LAST:event_newspaperActionPerformed
Outgoing Methods (calls):
experimental.DialogueBoxTester.selectEngineActionPerformed
Javadoc:
No Javadoc available
Method code:
private void selectEngineActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_selectEngineActionPerformed
// Add your handling code here:
dialogueBoxController.showSelectEngine();
}// GEN-LAST:event_selectEngineActionPerformed
Outgoing Methods (calls):
experimental.DialogueBoxTester.selectTrainOrdersActionPerformed
Javadoc:
No Javadoc available
Method code:
private void selectTrainOrdersActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_selectTrainOrdersActionPerformed
// Add your handling code here:
trainDialogueJPanel.setup(modelRoot, vl, closeCurrentDialogue);
trainDialogueJPanel.display(0);
dialogueBoxController.showContent(trainDialogueJPanel);
}// GEN-LAST:event_selectTrainOrdersActionPerformed
Outgoing Methods (calls):
experimental.DialogueBoxTester.selectWagonsActionPerformed
Javadoc:
No Javadoc available
Method code:
private void selectWagonsActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_selectWagonsActionPerformed
// Add your handling code here:
dialogueBoxController.showSelectWagons();
}// GEN-LAST:event_selectWagonsActionPerformed
Outgoing Methods (calls):
experimental.DialogueBoxTester.showCargoWaitingAndDemandActionPerformed
Javadoc:
No Javadoc available
Method code:
private void showCargoWaitingAndDemandActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showCargoWaitingAndDemandActionPerformed
// Add your handling code here:
CargoWaitingAndDemandedJPanel panel = new CargoWaitingAndDemandedJPanel();
panel.setup(modelRoot, vl, closeCurrentDialogue);
int newStationID = 0;
panel.display(newStationID);
dialogueBoxController.showContent(panel);
}// GEN-LAST:event_showCargoWaitingAndDemandActionPerformed
Outgoing Methods (calls):
experimental.DialogueBoxTester.showControlsActionPerformed
Javadoc:
No Javadoc available
Method code:
private void showControlsActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showControlsActionPerformed
// Add your handling code here:
dialogueBoxController.showGameControls();
}// GEN-LAST:event_showControlsActionPerformed
Outgoing Methods (calls):
experimental.DialogueBoxTester.showJavaSystemPropertiesActionPerformed
Javadoc:
No Javadoc available
Method code:
private void showJavaSystemPropertiesActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showJavaSystemPropertiesActionPerformed
// Add your handling code here:
String s = ShowJavaProperties.getPropertiesHtmlString();
HtmlJPanel htmlPanel = new HtmlJPanel(s);
htmlPanel.setup(modelRoot, vl, closeCurrentDialogue);
dialogueBoxController.showContent(htmlPanel);
}// GEN-LAST:event_showJavaSystemPropertiesActionPerformed
Outgoing Methods (calls):
experimental.DialogueBoxTester.showNetworthGraphActionPerformed
Javadoc:
No Javadoc available
Method code:
private void showNetworthGraphActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showNetworthGraphActionPerformed
dialogueBoxController.showNetworthGraph();
}// GEN-LAST:event_showNetworthGraphActionPerformed
Outgoing Methods (calls):
experimental.DialogueBoxTester.showStationInfoActionPerformed
Javadoc:
No Javadoc available
Method code:
private void showStationInfoActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showStationInfoActionPerformed
// Add your handling code here:
int stationNumber = 0;
dialogueBoxController.showStationInfo(stationNumber);
}// GEN-LAST:event_showStationInfoActionPerformed
Outgoing Methods (calls):
experimental.DialogueBoxTester.showTerrainInfoActionPerformed
Javadoc:
No Javadoc available
Method code:
private void showTerrainInfoActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showTerrainInfoActionPerformed
// Add your handling code here:
int terrainType = 0;
dialogueBoxController.showTerrainInfo(terrainType);
}// GEN-LAST:event_showTerrainInfoActionPerformed
Outgoing Methods (calls):
experimental.DialogueBoxTester.showTrainListActionPerformed
Javadoc:
No Javadoc available
Method code:
private void showTrainListActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showTrainListActionPerformed
// Add your handling code here:
dialogueBoxController.showTrainList();
}// GEN-LAST:event_showTrainListActionPerformed
Outgoing Methods (calls):
experimental.DistanceComparator.compare
Javadoc:
No Javadoc available
Method code:
@Override
public int compare(CityModel a, CityModel b) {
return distSquared(a) - distSquared(b);
}
Outgoing Methods (calls):
experimental.DistanceComparator.distSquared
Javadoc:
No Javadoc available
Method code:
int distSquared(CityModel a) {
int xDist = a.getCityX() - targetX;
int yDist = a.getCityY() - targetY;
return xDist * xDist + yDist * yDist;
}
Outgoing Methods (calls):
experimental.ExptWriteToBuffer.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
try {
Point p = new Point(10, 10);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objectOut = new ObjectOutputStream(out);
objectOut.writeObject(p);
objectOut.flush();
byte[] bytes = out.toByteArray();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ObjectInputStream objectIn = new ObjectInputStream(in);
Object o = objectIn.readObject();
Point p2 = (Point) o;
if (p.equals(p2)) {
logger.info("The two objects are equal!");
} else {
logger.info("The two objects are not equal!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
No outgoing methods.
experimental.GenerateDependenciesXmlAndHtml.add
Javadoc:
No Javadoc available
Method code:
private void add(String[] packageNames) {
assert started;
assert startedBlock;
String packagesString = "";
for (int i = packageNames.length - 1; i > 0; i--) {
packagesString += convertToPackageName(packageNames[i]) + ", ";
}
packagesString += " " + convertToPackageName(packageNames[0]);
// The html writer will use this later.
packages.add(packagesString);
xmlWriter.write("\n\t\t<!-- New row: " + packagesString + " -->\n");
xmlWriter.write("\t\t<echo message=\"New row: " + packagesString
+ "\"/>\n");
// Include the source files we are going to compile.
for (String packageName : packageNames) {
xmlWriter.write("\t\t<echo message=\"Check dependencies for "
+ packageName + "\"/>\n");
xmlWriter.write("\t\t<delete dir=\"temp\" />\n");
xmlWriter.write("\t\t<mkdir dir=\"temp\" />\n");
// First copy the files we are testing.
xmlWriter.write("\t\t<copy todir=\"temp\">\n");
xmlWriter.write("\t\t<fileset dir=\"src\">\n");
xmlWriter.write("\t\t\t<include name=\"" + packageName
+ ".java\" />\n");
// Exclude unit tests.
xmlWriter.write("\t\t\t<exclude name=\"**/*Test.java\" />\n");
xmlWriter.write("\t\t</fileset>\n");
xmlWriter.write("\t\t</copy>\n");
xmlWriter
.write("\t\t<javac fork=\"true\" srcdir=\"temp\" source=\"1.5\" classpath=\"dependencies\">\n");
// Include the files we are going to compile.
xmlWriter.write("\t\t\t<include name=\"" + packageName
+ ".java\" />\n");
xmlWriter.write("\t\t</javac>\n");
xmlWriter.write("\t\t<delete dir=\"temp\" />\n");
}
// Copy the files we have just tested to the dependencies directory.
xmlWriter.write("\t\t<copy todir=\"dependencies\">\n");
xmlWriter.write("\t\t<fileset dir=\"build\">\n");
for (int i = 0; i < packageNames.length; i++) {
xmlWriter.write("\t\t\t<include name=\"" + packageNames[i]
+ ".class\" />\n");
}
xmlWriter.write("\t\t\t<exclude name=\"**/*Test.class\" />\n");
xmlWriter.write("\t\t</fileset>\n");
xmlWriter.write("\t\t</copy>\n");
}
Outgoing Methods (calls):
experimental.GenerateDependenciesXmlAndHtml.convertToPackageName
Javadoc:
No Javadoc available
Method code:
private String convertToPackageName(String packagesString) {
if (!isPackageNameOk(packagesString)) {
throw new IllegalArgumentException(packagesString);
}
packagesString = packagesString.replace('/', '.');
/*
* Remove the last two characters, so that jfreerails.world.**.* - >
* jfreerails.world.** and jfreerails.util.* -> jfreerails.util
*/
packagesString = packagesString.substring(0,
packagesString.length() - 2);
return packagesString;
}
Outgoing Methods (calls):
experimental.GenerateDependenciesXmlAndHtml.endBlock
Javadoc:
No Javadoc available
Method code:
private void endBlock() {
assert started;
assert startedBlock;
htmlWriter
.write("<table width=\"100%\" border=\"1\" cellpadding=\"10\" cellspacing=\"10\" bordercolor=\"#333333\" bgcolor=\"#FFFFFF\">\n");
for (int i = packages.size() - 1; i >= 0; i--) {
String packageName = packages.get(i);
htmlWriter.write("<tr bgcolor=\"#FFCCCC\"> \n");
htmlWriter.write("<td height=\"50\" bgcolor=\"#FFCC66\">"
+ packageName + "</td>\n");
htmlWriter.write("</tr>\n");
}
htmlWriter.write("</table>\n");
packages.clear();
xmlWriter.write("\n\t\t<!-- End Block -->\n");
xmlWriter.write("\t\t<echo message=\"End Block\"/>\n");
startedBlock = false;
}
No outgoing methods.
experimental.GenerateDependenciesXmlAndHtml.finish
Javadoc:
No Javadoc available
Method code:
private void finish() {
assert started;
assert !startedBlock;
// finish the file.
xmlWriter.write("\t\t<delete dir=\"temp\" />\n");
xmlWriter.write("\t\t<delete dir=\"dependencies\" />\n");
xmlWriter.write("\t</target>\n");
xmlWriter.write("</project>\n");
htmlWriter.write("</html>\n");
started = false;
}
No outgoing methods.
experimental.GenerateDependenciesXmlAndHtml.isPackageNameOk
Javadoc:
No Javadoc available
Method code:
static boolean isPackageNameOk(String s) {
return s.matches("(([a-zA-Z]*)/)*\\*")
|| s.matches("(([a-zA-Z]*)/)*\\*\\*/\\*");
}
No outgoing methods.
experimental.GenerateDependenciesXmlAndHtml.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
try {
new GenerateDependenciesXmlAndHtml("checkdep.xml", "src"
+ File.separator + "docs" + File.separator
+ "dependencies.html");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
No outgoing methods.
experimental.GenerateDependenciesXmlAndHtml.start
Javadoc:
No Javadoc available
Method code:
private void start() {
assert !started;
startXml();
htmlWriter.write("<html>\n");
htmlWriter.write("<title>Dependencies between packages</title>\n");
htmlWriter.write("<p><code>This file was generate by " + sig
+ "</code></p>\n");
htmlWriter.write("<h1>Dependencies between packages</h1>\n");
htmlWriter
.write("<p>The figures below show the dependencies: packages may only depend, i.e. import classes and interfaces, from packages below.</p>\n");
started = true;
}
Outgoing Methods (calls):
experimental.GenerateDependenciesXmlAndHtml.startBlock
Javadoc:
No Javadoc available
Method code:
private void startBlock(String blockName) {
assert started;
assert !startedBlock;
startedBlock = true;
htmlWriter.write("<h2>" + blockName + "</h2>");
xmlWriter
.write("\n\t\t<!-- Setup the directory where the legal dependencies are stored -->\n");
xmlWriter.write("\t\t<delete dir=\"dependencies\" />\n");
xmlWriter.write("\t\t<mkdir dir=\"dependencies\" />\n");
}
No outgoing methods.
experimental.GenerateDependenciesXmlAndHtml.startXml
Javadoc:
No Javadoc available
Method code:
private void startXml() {
// Start the file.
xmlWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
xmlWriter
.write("<project basedir=\".\" default=\"checkdep\" name=\"checkdep\">\n");
xmlWriter.write("\t<description>This ant script was generated by "
+ sig
+ " to check the dependencies for jfreerails.</description>\n");
// Set the properties.
// Add the compile target.
xmlWriter
.write("\n\t<target description=\"Build everything except JUnit test-classes\" name=\"compile\">\n");
xmlWriter.write("\t\t<mkdir dir=\"build\" />\n");
xmlWriter
.write("\t\t<javac destdir=\"build\" fork=\"true\" srcdir=\"src\" source=\"1.5\">\n");
xmlWriter.write("\t\t\t<exclude name=\"**/*Test.java\" />\n");
xmlWriter.write("\t\t </javac>\n");
xmlWriter.write("\t</target>\n");
// Start the check depend target.
xmlWriter
.write("\n\n\t<target depends=\"compile\" description=\"Tests whether dependencies between packages conform to the rules defined in this target\" name=\"checkdep\">\n");
}
No outgoing methods.
experimental.GenerateDependenciesXmlAndHtmlTest.testIsPackageNameOk
Javadoc:
No Javadoc available
Method code:
public void testIsPackageNameOk() {
assertTrue(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/*"));
assertFalse(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails.*"));
assertTrue(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/trees/*"));
assertFalse(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/trees/branches*"));
assertTrue(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/trees/branches/*"));
assertFalse(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/trees/branches/**/"));
assertTrue(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/trees/branches/**/*"));
assertTrue(GenerateDependenciesXmlAndHtml
.isPackageNameOk("it/unimi/dsi/fastUtil/*")); // note upper
// case in
// package name.
}
Outgoing Methods (calls):
experimental.GenerateTrainHighlights.gen
Javadoc:
No Javadoc available
Method code:
public static void gen(ImageManager imageManager, Color selection, String filename) {
for (Step step : Step.getList()) {
int tileSize = 30;
Image smallImage = imageManager.newBlankImage(tileSize, tileSize);
Graphics2D g2 = (Graphics2D) smallImage.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(3));
double arcRadius = 5;
g2.rotate(step.getDirection(), tileSize/2, tileSize/2);
RoundRectangle2D roundedRectangle = new RoundRectangle2D.Double(7, 3, 16, 26, arcRadius, arcRadius);
g2.setColor(selection);
g2.fill(roundedRectangle);
g2.dispose();
String name = String.format(filename, step.toAbrvString());
imageManager.setImage(name, smallImage);
}
}
Outgoing Methods (calls):
experimental.GenerateTrainHighlights.main
Javadoc:
/** * @param args the command line arguments */
Method code:
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ImageManager imageManager = new ImageManagerImpl(
"/experimental/", "/experimental/");
UIDefaults lookAndFeelDefaults = UIManager.getLookAndFeelDefaults();
Color selection = (Color) lookAndFeelDefaults.get("List.selectionBackground");
selection = makeTransparent(selection, 128);
String filename = "selected_%s.png";
gen(imageManager, selection, filename);
Color focus = (Color) lookAndFeelDefaults.get("TabbedPane.focus");
focus = makeTransparent(focus, 128);
filename = "focused_%s.png";
gen(imageManager, focus, filename);
try {
imageManager.writeAllImages();
} catch (IOException e) {
e.printStackTrace();
}
}
Outgoing Methods (calls):
experimental.GenerateTrainHighlights.makeTransparent
Javadoc:
No Javadoc available
Method code:
static Color makeTransparent(Color before, int alpha){
return new Color(before.getRed(), before.getGreen(), before.getBlue(), alpha);
}
No outgoing methods.
experimental.LineDrawTrackPieceView.drawTrackPieceIcon
Javadoc:
No Javadoc available
Method code:
public void drawTrackPieceIcon(int trackTemplate, java.awt.Graphics g,
int x, int y, java.awt.Dimension tileSize) {
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new java.awt.BasicStroke(8.0f));
g2.setColor(java.awt.Color.red);
if (0 != trackTemplate) {
int drawX = x * tileSize.width;
int drawY = y * tileSize.height;
// g.drawLine(drawX-10,drawY-10,drawX+10,drawY+10);
for (int i = 0; i < 9; i++) {
if ((trackTemplate & (1 << i)) == (1 << i)) {
g2.drawLine(drawX + 15, drawY + 15,
drawX + 15 + 15 * xx[i], drawY + 15 + 15 * yy[i]);
}
}
}
}
No outgoing methods.
experimental.LineDrawTrackPieceView.dumpImages
Javadoc:
No Javadoc available
Method code:
public void dumpImages(ImageManager imageManager) {
// TODO Auto-generated method stub
}
No outgoing methods.
experimental.LineDrawTrackPieceView.getTrackPieceIcon
Javadoc:
No Javadoc available
Method code:
public java.awt.Image getTrackPieceIcon(int trackTemplate) {
return null;
}
No outgoing methods.
experimental.RunMe.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
JFrame jFrame = new jfreerails.client.top.ClientJFrame(
new SimpleComponentFactoryImpl2());
// jFrame.show();
ScreenHandler screenHandler = new ScreenHandler(jFrame,
ScreenHandler.WINDOWED_MODE);
GameLoop gameLoop = new GameLoop(screenHandler);
Thread t = new Thread(gameLoop);
t.start();
}
No outgoing methods.
experimental.SimpleComponentFactoryImpl2.addMainMapAndOverviewMapMediatorIfNecessary
Javadoc:
No Javadoc available
Method code:
private void addMainMapAndOverviewMapMediatorIfNecessary() {
if (this.mainMap != null && this.overviewMap != null
&& null == this.mediator) {
// Rectangle r = this.overviewMap.getMainMapVisibleRect();
this.mediator = new MainMapAndOverviewMapMediator(overviewMap,
mainMapScrollPane1.getViewport(), mainMap, r);
}
}
No outgoing methods.
experimental.SimpleComponentFactoryImpl2.addMainmapzoomMenuItem
Javadoc:
No Javadoc available
Method code:
private void addMainmapzoomMenuItem(JMenu displayMenu, final float scale) {
String menuItemName = "Set main map scale=" + scale;
JMenuItem menuItem = new JMenuItem(menuItemName);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Rectangle visRect = mainMap.getVisibleRect();
int oldWidth = mainMap.getWidth();
mainMap.setup(new BlankMapRenderer(scale));
int newWidth = mainMap.getPreferredSize().width;
int oldCenterX = visRect.x + (visRect.width / 2);
int newCenterX = oldCenterX * newWidth / oldWidth;
visRect.x = newCenterX - visRect.width / 2;
int oldCenterY = visRect.y + (visRect.height / 2);
int newCenterY = oldCenterY * newWidth / oldWidth;
visRect.y = newCenterY - visRect.height / 2;
/*
* LL: I'm not sure why the 'if' is necessary in the following,
* but the view does not center on the right spot without it.
*/
if (oldWidth < newWidth) {
mainMap.setSize(mainMap.getPreferredSize());
mainMap.scrollRectToVisible(visRect);
} else {
mainMap.scrollRectToVisible(visRect);
mainMap.setSize(mainMap.getPreferredSize());
}
}
});
displayMenu.add(menuItem);
}
Outgoing Methods (calls):
experimental.SimpleComponentFactoryImpl2.addOverviewmapzoomMenuItem
Javadoc:
No Javadoc available
Method code:
private void addOverviewmapzoomMenuItem(JMenu displayMenu, final float scale) {
String menuItemName = "Set overview map scale=" + scale;
JMenuItem menuItem = new JMenuItem(menuItemName);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
overviewMap.setup(new BlankMapRenderer(scale));
}
});
displayMenu.add(menuItem);
}
Outgoing Methods (calls):
experimental.SimpleComponentFactoryImpl2.createBrokerMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createBrokerMenu() {
JMenu brokerMenu = new JMenu("Broker");
return brokerMenu;
}
No outgoing methods.
experimental.SimpleComponentFactoryImpl2.createBuildMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createBuildMenu() {
return new JMenu("Build");
}
No outgoing methods.
experimental.SimpleComponentFactoryImpl2.createCashJLabel
Javadoc:
No Javadoc available
Method code:
public JLabel createCashJLabel() {
return null;
}
No outgoing methods.
experimental.SimpleComponentFactoryImpl2.createDateJLabel
Javadoc:
No Javadoc available
Method code:
public JLabel createDateJLabel() {
return null;
}
No outgoing methods.
experimental.SimpleComponentFactoryImpl2.createDisplayMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createDisplayMenu() {
JMenu displayMenu = new JMenu("Display");
addMainmapzoomMenuItem(displayMenu, 5);
addMainmapzoomMenuItem(displayMenu, 10);
addOverviewmapzoomMenuItem(displayMenu, 0.2F);
addOverviewmapzoomMenuItem(displayMenu, 0.6F);
return displayMenu;
}
Outgoing Methods (calls):
experimental.SimpleComponentFactoryImpl2.createGameMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createGameMenu() {
return new JMenu("Game");
}
No outgoing methods.
experimental.SimpleComponentFactoryImpl2.createHelpMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createHelpMenu() {
return null;
}
No outgoing methods.
experimental.SimpleComponentFactoryImpl2.createMainMap
Javadoc:
No Javadoc available
Method code:
public JScrollPane createMainMap() {
if (null == this.mainMap) {
// this.mainMap = new MapJPanel();
this.mainMap = new MapViewJComponentConcrete();
mainMapScrollPane1 = new JScrollPane();
mainMapScrollPane1.setViewportView(this.mainMap);
addMainMapAndOverviewMapMediatorIfNecessary();
}
return mainMapScrollPane1;
}
Outgoing Methods (calls):
experimental.SimpleComponentFactoryImpl2.createOverviewMap
Javadoc:
No Javadoc available
Method code:
public JPanel createOverviewMap() {
if (null == this.overviewMap) {
// this.overviewMap = new OverviewMapJPanel();
this.overviewMap = new OverviewMapJComponent(r);
this.overviewMap.setup(new BlankMapRenderer(0.4F));
addMainMapAndOverviewMapMediatorIfNecessary();
}
return overviewMap;
// return new TestPanel();
}
Outgoing Methods (calls):
experimental.SimpleComponentFactoryImpl2.createReportsMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createReportsMenu() {
// TODO Auto-generated method stub
return null;
}
No outgoing methods.
experimental.SimpleComponentFactoryImpl2.createTrainsJTabPane
Javadoc:
No Javadoc available
Method code:
public JTabbedPane createTrainsJTabPane() {
return null;
}
No outgoing methods.
experimental.SimpleMoveReceiver.processMove
Javadoc:
No Javadoc available
Method code:
public void processMove(Move move) {
move.doMove(w, Player.AUTHORITATIVE);
}
Outgoing Methods (calls):
experimental.SimpleMoveReceiver.processPreMove
Javadoc:
No Javadoc available
Method code:
public void processPreMove(PreMove pm) {
processMove(pm.generateMove(w));
}
Outgoing Methods (calls):
experimental.SimpleMoveReceiver.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(Move move) {
return move.tryDoMove(w, Player.AUTHORITATIVE);
}
Outgoing Methods (calls):
experimental.TestLogging.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
Logger logger1 = Logger.getLogger(TestLogging.class.getName());
logger1.info("Logging properties file: "
+ System.getProperty("java.util.logging.config.file"));
logger1.severe("Hello severe logging");
logger1.warning("Hello warning logging");
logger1.info("Hello info logging");
logger1.fine("Hello fine logging");
logger1.finer("Hello finer logging");
logger1.finest("Hello finest logging");
}
No outgoing methods.
experimental.TrackRenderer.controlPoint
Javadoc:
/** * Calculates a control point based on the given source point. * The new point is computed by applying a weight of 0.3 to the source coordinates * and adjusting them relative to the tile width. This transformation is used * to position control points for rendering purposes. * * @param from The source point used to compute the control point. * @return A new Point2D.Double representing the transformed control point. */
Method code:
private Point2D.Double controlPoint(Point2D.Double from) {
double weight = 0.3;
double x = from.getX() * weight + tileWidth * (1 - weight);
double y = from.getY() * weight + tileWidth * (1 - weight);
return new Point2D.Double(x, y);
}
No outgoing methods.
experimental.TrackRenderer.createAdjacentCurve
Javadoc:
No Javadoc available
Method code:
public static CubicCurve2D.Double createAdjacentCurve(
CubicCurve2D.Double c, double shift1, double shift2) {
Line2D.Double line1 = new Line2D.Double(c.getX1(), c.getY1(), c
.getCtrlX1(), c.getCtrlY1());
Line2D.Double line2 = new Line2D.Double(c.getX2(), c.getY2(), c
.getCtrlX2(), c.getCtrlY2());
line1 = createParallelLine(line1, shift1);
line2 = createParallelLine(line2, -shift2);
return new CubicCurve2D.Double(line1.x1, line1.y1, line1.x2, line1.y2,
line2.x2, line2.y2, line2.x1, line2.y1);
}
Outgoing Methods (calls):
experimental.TrackRenderer.createParallelLine
Javadoc:
No Javadoc available
Method code:
public static Line2D.Double createParallelLine(Line2D.Double line,
double shift) {
Line2D.Double returnValue = new Line2D.Double(line.getP1(), line
.getP2());
double distance = line.getP1().distance(line.getP2());
double dRatio = shift / distance;
double dx = (line.x1 - line.x2) * dRatio;
double dy = (line.y1 - line.y2) * dRatio;
returnValue.x1 -= dy;
returnValue.y1 += dx;
returnValue.x2 -= dy;
returnValue.y2 += dx;
return returnValue;
}
No outgoing methods.
experimental.TrackRenderer.getStroke4Curve
Javadoc:
/** * Generates the Stroke used to draw the sleepers for track section * represented by the specified curve. */
Method code:
/**
* Generates the Stroke used to draw the sleepers for track section
* represented by the specified curve.
*/
public BasicStroke getStroke4Curve(CubicCurve2D.Double curve) {
PathIterator fpt = curve.getPathIterator(new AffineTransform(), 0.01);
double length = 0;
double[] coords = new double[6];
double x, y;
fpt.currentSegment(coords);
double lastX = coords[0];
double lastY = coords[1];
for (; !fpt.isDone(); fpt.next()) {
fpt.currentSegment(coords);
x = coords[0];
y = coords[1];
double dx = x - lastX;
double dy = y - lastY;
length += Math.sqrt(dx * dx + dy * dy);
lastX = x;
lastY = y;
}
float sleepers = (float) length / (targetSleeperGap + sleeperWidth);
float sleeperCount = (int) sleepers;
float sleeperGap = (float) length / sleeperCount - sleeperWidth;
float dash1[] = { sleeperWidth, sleeperGap };
float phase = sleeperWidth + (sleeperGap / 2);
return new BasicStroke((float) sleeperLength, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, dash1, phase);
}
No outgoing methods.
experimental.TrackRenderer.paintTrack
Javadoc:
No Javadoc available
Method code:
void paintTrack(Graphics2D g, List<CubicCurve2D.Double> sections) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if (!tunnel) {
// Draw sleepers
g.setColor(sleepersColor);
for (CubicCurve2D.Double section : sections) {
BasicStroke dashed = getStroke4Curve(section);
g.setStroke(dashed);
g.draw(section);
}
g.setColor(railsColor);
} else {
g.setColor(Color.BLACK);
}
// Draw rails
g.setStroke(rail);
for (CubicCurve2D.Double section : sections) {
float halfGauge = gauge / 2;
CubicCurve2D.Double rail1 = createAdjacentCurve(section, halfGauge,
halfGauge);
CubicCurve2D.Double rail2 = createAdjacentCurve(section,
-halfGauge, -halfGauge);
g.draw(rail1);
g.draw(rail2);
}
}
Outgoing Methods (calls):
experimental.TrackRenderer.paintTrackConf
Javadoc:
No Javadoc available
Method code:
void paintTrackConf(Graphics2D g2, TrackConfiguration conf) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Draw title
// String title = BinaryNumberFormatter.formatWithLowBitOnLeft(conf
// .get9bitTemplate(), 9);
// g.setColor(Color.BLACK);
// g.setFont(font);
//
// g.drawString(title, 10, 10);
Step[] directions = Step.getList();
List<CubicCurve2D.Double> sections = new ArrayList<CubicCurve2D.Double>();
int matches = 0;
for (int i = 0; i < directions.length - 2; i++) {
if (conf.contains(directions[i])) {
// System.out.println("\n"+directions[i]+" to ..");
int maxJ = Math.min(i + 7, directions.length);
for (int j = i + 2; j < maxJ; j++) {
// System.out.println(directions[j]);
if (conf.contains(directions[j])) {
Double toCurve = toCurve(directions[i], directions[j]);
if (doubleTrack) {
sections.add(createAdjacentCurve(toCurve,
doubleTrackGap, doubleTrackGap));
sections.add(createAdjacentCurve(toCurve,
-doubleTrackGap, -doubleTrackGap));
} else {
sections.add(toCurve);
}
matches++;
}
}
}
}
if (matches == 0) {
for (int i = 0; i < directions.length; i++) {
if (conf.contains(directions[i])) {
Double toCurve = toCurve(directions[i]);
if (doubleTrack) {
sections.add(createAdjacentCurve(toCurve,
doubleTrackGap, doubleTrackGap));
sections.add(createAdjacentCurve(toCurve,
-doubleTrackGap, -doubleTrackGap));
} else {
sections.add(toCurve);
}
}
}
}
paintTrack(g2, sections);
}
Outgoing Methods (calls):
experimental.TrackRenderer.setIcon
Javadoc:
No Javadoc available
Method code:
void setIcon(String typeName) {
try {
String relativeFileName = "icons" + File.separator + typeName
+ ".png";
relativeFileName = relativeFileName.replace(' ', '_');
Image im = imageManager.getImage(relativeFileName);
icon = im;
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException(e);
}
}
Outgoing Methods (calls):
experimental.TrackRenderer.toCurve
Javadoc:
No Javadoc available
Method code:
CubicCurve2D.Double toCurve(Step a, Step b) {
float halfTile = tileWidth / 2;
Point2D.Double start, end, one, two;
start = new Point2D.Double();
start.x = tileWidth + (halfTile * a.deltaX);
start.y = tileWidth + (halfTile * a.deltaY);
one = controlPoint(start);
end = new Point2D.Double();
end.x = tileWidth + (halfTile * b.deltaX);
end.y = tileWidth + (halfTile * b.deltaY);
two = controlPoint(end);
CubicCurve2D.Double returnValue = new CubicCurve2D.Double();
returnValue.setCurve(start, one, two, end);
return returnValue;
}
Outgoing Methods (calls):
experimental.TrackTilesGenerator.controlPoint
Javadoc:
No Javadoc available
Method code:
private Point2D.Double controlPoint(Point2D.Double from) {
double weight = 0.3;
double x = from.getX() * weight + 300 * (1 - weight);
double y = from.getY() * weight + 300 * (1 - weight);
return new Point2D.Double(x, y);
}
No outgoing methods.
experimental.TrackTilesGenerator.generateTiles
Javadoc:
No Javadoc available
Method code:
private void generateTiles() {
for (TrackRule rule : rules) {
TrackRule.TrackCategories category = rule.getCategory();
Image icon;
if (category.equals(TrackRule.TrackCategories.bridge)
|| category.equals(TrackRule.TrackCategories.station)) {
tr.setIcon(rule.getTypeName());
icon = tr.icon;
} else {
icon = null;
}
if (category.equals(TrackRule.TrackCategories.tunnel)) {
tr.tunnel = true;
} else {
tr.tunnel = false;
}
tr.doubleTrack = rule.isDouble();
for (int i = 0; i < 512; i++) {
if (rule.testTrackPieceLegality(i)) {
String fileName = TrackPieceRendererImpl.generateFilename(
i, rule.getTypeName());
TrackConfiguration conf = TrackConfiguration
.from9bitTemplate(i);
Image smallImage = imageManager.newBlankImage(60, 60);
Graphics2D g2 = (Graphics2D) smallImage.getGraphics();
tr.paintTrackConf(g2, conf);
// Draw icon. Used for bridges and stations.
if (null != icon) {
int x = 30 - icon.getWidth(null) / 2;
int y = 30 - icon.getHeight(null) / 2;
g2.drawImage(icon, x, y, null);
}
g2.dispose();
imageManager.setImage(fileName, smallImage);
}
}
}
try {
imageManager.writeAllImages();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Outgoing Methods (calls):
experimental.TrackTilesGenerator.getSize4Panel
Javadoc:
No Javadoc available
Method code:
private Dimension getSize4Panel() {
int height = 90 * rules.size();
int width = 0;
int lastWidth = 0;
for (TrackRule rule : rules) {
width = Math.max(width, lastWidth);
lastWidth = 0;
Iterator<TrackConfiguration> it = rule
.getLegalConfigurationsIterator();
while (it.hasNext()) {
lastWidth += 60;
}
}
return new Dimension(width, height);
}
Outgoing Methods (calls):
experimental.TrackTilesGenerator.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
JFrame frame = new JFrame();
JScrollPane scrollPane = new JScrollPane();
frame.add(scrollPane);
TrackTilesGenerator trackTilesGenerator = new TrackTilesGenerator();
trackTilesGenerator.setPreferredSize(trackTilesGenerator
.getSize4Panel());
scrollPane.setViewportView(trackTilesGenerator);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
Outgoing Methods (calls):
experimental.TrackTilesGenerator.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (TrackRule rule : rules) {
String typeName = rule.getTypeName();
typeName += rule.isDouble() ? " (Double) " : " (Single)";
g.drawString(typeName, 10, 10);
g.translate(0, 30);
Graphics2D g2 = (Graphics2D) g.create();
for (int i = 0; i < 512; i++) {
if (rule.testTrackPieceLegality(i)) {
String fileName = TrackPieceRendererImpl.generateFilename(
i, rule.getTypeName());
Image tile;
try {
tile = imageManager.getImage(fileName);
g2.drawImage(tile, 0, 0, null);
g2.translate(60, 0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
g.translate(0, 60);
}
}
Outgoing Methods (calls):
experimental.TrainMotionExpt.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
System.setProperty("SHOWFPS", "true");
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.getContentPane().add(new TrainMotionExpt());
ScreenHandler screenHandler = new ScreenHandler(f,
ScreenHandler.WINDOWED_MODE);
screenHandler.apply();
GameLoop gameLoop = new GameLoop(screenHandler);
Thread t = new Thread(gameLoop);
t.start();
}
Outgoing Methods (calls):
experimental.TrainMotionExpt.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Shade tiles with track..
g.setColor(Color.GREEN);
for (int x = 0; x < world.getMapWidth(); x++) {
for (int y = 0; y < world.getMapHeight(); y++) {
FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
if (tile.getTrackPiece().getTrackTypeID() != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
int w = Step.TILE_DIAMETER;
int h = Step.TILE_DIAMETER;
g.drawRect(x * Step.TILE_DIAMETER, y * Step.TILE_DIAMETER,
w, h);
}
}
}
long l = System.currentTimeMillis() - startTime;
double ticks = (double) l / 1000;
while (ticks > finishTime) {
updateTrainPosition();
}
ActivityIterator ai = world.getActivities(principal, 0);
while (ai.getFinishTime() < ticks && ai.hasNext()) {
ai.nextActivity();
}
double t = Math.min(ticks, ai.getFinishTime());
t = t - ai.getStartTime();
TrainMotion motion = (TrainMotion) ai.getActivity();
TrainPositionOnMap pos = (TrainPositionOnMap) ai.getState(ticks);
PathOnTiles pathOT = motion.getPath();
Iterator<ImPoint> it = pathOT.tiles();
while (it.hasNext()) {
ImPoint tile = it.next();
int x = tile.x * Step.TILE_DIAMETER;
int y = tile.y * Step.TILE_DIAMETER;
int w = Step.TILE_DIAMETER;
int h = Step.TILE_DIAMETER;
g.setColor(Color.WHITE);
g.fillRect(x, y, w, h);
g.setColor(Color.DARK_GRAY);
g.drawRect(x, y, w, h);
}
pathOT = motion.getTiles(t);
it = pathOT.tiles();
while (it.hasNext()) {
ImPoint tile = it.next();
int x = tile.x * Step.TILE_DIAMETER;
int y = tile.y * Step.TILE_DIAMETER;
int w = Step.TILE_DIAMETER;
int h = Step.TILE_DIAMETER;
g.setColor(Color.LIGHT_GRAY);
g.fillRect(x, y, w, h);
g.setColor(Color.DARK_GRAY);
g.drawRect(x, y, w, h);
}
g.setColor(Color.BLACK);
IntLine line = new IntLine();
FreerailsPathIterator path = pos.path();
while (path.hasNext()) {
path.nextSegment(line);
g.drawLine(line.x1, line.y1, line.x2, line.y2);
}
int speed = (int) Math.round(pos.getSpeed());
g.drawString("Speed: " + speed, 260, 60);
}
Outgoing Methods (calls):
experimental.TrainMotionExpt.updateTrainPosition
Javadoc:
No Javadoc available
Method code:
private void updateTrainPosition() {
Random rand = new Random(System.currentTimeMillis());
MoveTrainPreMove moveTrain = new MoveTrainPreMove(0, principal);
Move m;
if (rand.nextInt(10) == 0) {
m = moveTrain.stopTrain(world);
} else {
m = moveTrain.generateMove(world);
}
MoveStatus ms = m.doMove(world, principal);
if (!ms.ok)
throw new IllegalStateException(ms.message);
ActivityIterator ai = world.getActivities(principal, 0);
while (ai.hasNext()) {
ai.nextActivity();
finishTime = ai.getFinishTime();
}
}
Outgoing Methods (calls):
experimental.Unknown.actionPerformed
Javadoc:
No Javadoc available
Method code:
public void actionPerformed(ActionEvent arg0) {
dialogueBoxController.closeContent();
}
Outgoing Methods (calls):
jfreerails.client.common.ActionAdapter.getActions
Javadoc:
/** * @return an enumeration of Action */
Method code:
/**
* @return an enumeration of Action
*/
public Enumeration<Action> getActions() {
return new Enumeration<Action>() {
private int i = 0;
public boolean hasMoreElements() {
return (i < actions.length);
}
public Action nextElement() {
return actions[i++];
}
};
}
No outgoing methods.
jfreerails.client.common.ActionAdapter.getButtonModels
Javadoc:
/** * @return an enumeration of MappedButtonModel */
Method code:
/**
* @return an enumeration of MappedButtonModel
*/
public Enumeration<MappedButtonModel> getButtonModels() {
return buttonModels.elements();
}
No outgoing methods.
jfreerails.client.common.ActionAdapter.setPerformActionOnSetSelectedItem
Javadoc:
No Javadoc available
Method code:
public void setPerformActionOnSetSelectedItem(
boolean performActionOnSetSelectedItem) {
this.performActionOnSetSelectedItem = performActionOnSetSelectedItem;
}
No outgoing methods.
jfreerails.client.common.ActionAdapter.setSelectedItem
Javadoc:
/** * @param item * The NAME of the Action selected */
Method code:
/**
* @param item
* The NAME of the Action selected
*/
@Override
public void setSelectedItem(Object item) {
// only set the item if not already selected
if ((item != null) && item.equals(getSelectedItem())) {
return;
}
super.setSelectedItem(item);
// stop addElement from triggering actions
if (!initialised) {
return;
}
for (int i = 0; i < buttonModels.size(); i++) {
MappedButtonModel bm = buttonModels.get(i);
if (bm.actionName.equals(item)) {
bm.setSelected(true);
}
}
if (performActionOnSetSelectedItem) {
for (int i = 0; i < actions.length; i++) {
if (actions[i].getValue(Action.NAME).equals(item)) {
actions[i].actionPerformed(new ActionEvent(this,
ActionEvent.ACTION_PERFORMED, (String) actions[i]
.getValue(Action.ACTION_COMMAND_KEY)));
}
}
}
}
Outgoing Methods (calls):
jfreerails.client.common.BinaryNumberFormatter.format
Javadoc:
No Javadoc available
Method code:
public static String format(int i, int bits) {
int maxValue = 1 << (bits);
if (i < 0) {
throw new IllegalArgumentException(
"i must be greater than 0. It was " + i);
}
if (i >= maxValue) {
throw new IllegalArgumentException("i must be less than "
+ maxValue + ". It was " + i);
}
String s = Integer.toString(i + maxValue, 2);
String number = s.substring(1);
return number;
}
No outgoing methods.
jfreerails.client.common.BinaryNumberFormatter.formatWithLowBitOnLeft
Javadoc:
No Javadoc available
Method code:
public static String formatWithLowBitOnLeft(int i, int bits) {
StringBuffer buff = new StringBuffer(format(i, bits));
buff.reverse();
return buff.toString();
}
Outgoing Methods (calls):
jfreerails.client.common.BinaryNumberFormatterTest.testBinaryFormat
Javadoc:
No Javadoc available
Method code:
public void testBinaryFormat() {
assertEquals("0", BinaryNumberFormatter.format(0, 1));
assertEquals("1", BinaryNumberFormatter.format(1, 1));
assertEquals("00", BinaryNumberFormatter.format(0, 2));
assertEquals("01", BinaryNumberFormatter.format(1, 2));
assertEquals("10", BinaryNumberFormatter.format(2, 2));
assertEquals("11", BinaryNumberFormatter.format(3, 2));
assertEquals("1111", BinaryNumberFormatter.format(15, 4));
try {
BinaryNumberFormatter.format(-1, 2);
assertTrue(false);
} catch (IllegalArgumentException e) {
}
try {
BinaryNumberFormatter.format(4, 2);
assertTrue(false);
} catch (IllegalArgumentException e) {
}
}
Outgoing Methods (calls):
jfreerails.client.common.ImageManager.contains
Javadoc:
No Javadoc available
Method code:
boolean contains(String relativeFilename);
No outgoing methods.
jfreerails.client.common.ImageManager.getImage
Javadoc:
No Javadoc available
Method code:
Image getImage(String relativeFilename) throws IOException;
No outgoing methods.
jfreerails.client.common.ImageManager.getScaledImage
Javadoc:
No Javadoc available
Method code:
Image getScaledImage(String relativeFilename, int height)
throws IOException;
No outgoing methods.
jfreerails.client.common.ImageManager.newBlankImage
Javadoc:
No Javadoc available
Method code:
Image newBlankImage(int height, int width);
No outgoing methods.
jfreerails.client.common.ImageManager.setImage
Javadoc:
No Javadoc available
Method code:
void setImage(String relativeFilename, Image i);
No outgoing methods.
jfreerails.client.common.ImageManager.setPathToReadFrom
Javadoc:
No Javadoc available
Method code:
void setPathToReadFrom(String s);
No outgoing methods.
jfreerails.client.common.ImageManager.setPathToWriteTo
Javadoc:
No Javadoc available
Method code:
void setPathToWriteTo(String s);
No outgoing methods.
jfreerails.client.common.ImageManager.writeAllImages
Javadoc:
No Javadoc available
Method code:
void writeAllImages() throws IOException;
No outgoing methods.
jfreerails.client.common.ImageManager.writeImage
Javadoc:
No Javadoc available
Method code:
void writeImage(String relativeFilename) throws IOException;
No outgoing methods.
jfreerails.client.common.ImageManagerImpl.contains
Javadoc:
No Javadoc available
Method code:
public boolean contains(String relativeFilename) {
relativeFilename = relativeFilename.replace(' ', '_');
if (imageHashMap.containsKey(relativeFilename)) {
return true;
}
File f = new File(pathToWriteTo + File.separator + relativeFilename);
if (f.isFile()) {
return true;
}
return false;
}
No outgoing methods.
jfreerails.client.common.ImageManagerImpl.getImage
Javadoc:
No Javadoc available
Method code:
public Image getImage(String relativeFilename) throws IOException {
relativeFilename = relativeFilename.replace(' ', '_');
if (!isValid(relativeFilename))
throw new IllegalArgumentException(relativeFilename
+ " must match " + A_REGEX);
if (imageHashMap.containsKey(relativeFilename)) {
return imageHashMap.get(relativeFilename);
}
// File f = new File(pathToReadFrom+File.separator+relativeFilename);
String read = pathToReadFrom + relativeFilename;
read = read.replace(File.separatorChar, '/');
URL url = ImageManagerImpl.class.getResource(read);
if (null == url) {
throw new IOException("Couldn't find: " + read);
}
Image tempImage = ImageIO.read(url);
if (null == tempImage) {
throw new IOException("Couldn't find: " + read);
}
Image compatibleImage = defaultConfiguration.createCompatibleImage(
tempImage.getWidth(null), tempImage.getHeight(null),
Transparency.TRANSLUCENT);
Graphics g = compatibleImage.getGraphics();
g.drawImage(tempImage, 0, 0, null);
imageHashMap.put(relativeFilename, compatibleImage);
return compatibleImage;
}
Outgoing Methods (calls):
jfreerails.client.common.ImageManagerImpl.getScaledImage
Javadoc:
/** * Returns the specified image scaled so that its height is equal to the * specified height. */
Method code:
/**
* Returns the specified image scaled so that its height is equal to the
* specified height.
*/
public Image getScaledImage(String relativeFilename, int height)
throws IOException {
relativeFilename = relativeFilename.replace(' ', '_');
if (!isValid(relativeFilename))
throw new IllegalArgumentException(relativeFilename
+ " must match " + A_REGEX);
String hashKey = relativeFilename + height;
if (this.scaledImagesHashMap.containsKey(hashKey)) {
return scaledImagesHashMap.get(hashKey);
}
Image i = getImage(relativeFilename);
if (i.getHeight(null) == height) {
return i;
}
int width = (i.getWidth(null) * height) / i.getHeight(null);
Image compatibleImage = newBlankImage(height, width);
Graphics2D g = (Graphics2D) compatibleImage.getGraphics();
g.setRenderingHints(this.renderingHints);
g.drawImage(i, 0, 0, width, height, null);
scaledImagesHashMap.put(hashKey, compatibleImage);
return compatibleImage;
}
Outgoing Methods (calls):
jfreerails.client.common.ImageManagerImpl.isValid
Javadoc:
No Javadoc available
Method code:
public static boolean isValid(String s) {
Matcher m = pattern.matcher(s);
return m.matches();
}
No outgoing methods.
jfreerails.client.common.ImageManagerImpl.newBlankImage
Javadoc:
No Javadoc available
Method code:
public Image newBlankImage(int height, int width) {
Image compatibleImage = defaultConfiguration.createCompatibleImage(
width, height, Transparency.TRANSLUCENT);
return compatibleImage;
}
No outgoing methods.
jfreerails.client.common.ImageManagerImpl.setImage
Javadoc:
No Javadoc available
Method code:
public void setImage(String relativeFilename, Image i) {
relativeFilename = relativeFilename.replace(' ', '_');
if (i == null) {
throw new NullPointerException(relativeFilename);
}
imageHashMap.put(relativeFilename, i);
}
No outgoing methods.
jfreerails.client.common.ImageManagerImpl.setPathToReadFrom
Javadoc:
No Javadoc available
Method code:
public void setPathToReadFrom(String s) {
pathToReadFrom = s;
}
No outgoing methods.
jfreerails.client.common.ImageManagerImpl.setPathToWriteTo
Javadoc:
No Javadoc available
Method code:
public void setPathToWriteTo(String s) {
pathToWriteTo = s;
}
No outgoing methods.
jfreerails.client.common.ImageManagerImpl.writeAllImages
Javadoc:
No Javadoc available
Method code:
public void writeAllImages() throws IOException {
for (String s : imageHashMap.keySet()) {
writeImage(s);
}
}
Outgoing Methods (calls):
jfreerails.client.common.ImageManagerImpl.writeImage
Javadoc:
No Javadoc available
Method code:
public void writeImage(String relativeFilename) throws IOException {
if (null == pathToWriteTo)
throw new NullPointerException("null == pathToWriteTo");
relativeFilename = relativeFilename.replace(' ', '_');
File f = new File(pathToWriteTo + File.separator + relativeFilename);
if (imageHashMap.containsKey(relativeFilename)) {
RenderedImage i = (RenderedImage) imageHashMap
.get(relativeFilename);
String pathName = f.getPath();
File path = new File(pathName);
path.mkdirs();
ImageIO.write(i, "png", f);
logger.info("Writing " + f);
} else {
throw new NoSuchElementException(relativeFilename);
}
}
No outgoing methods.
jfreerails.client.common.ImageManagerImplTest.testIsValid
Javadoc:
No Javadoc available
Method code:
public void testIsValid() {
assertTrue(ImageManagerImpl.isValid("cursor/infomode.png"));
assertFalse(ImageManagerImpl.isValid("/cursor/infomode.png"));
}
Outgoing Methods (calls):
jfreerails.client.common.MappedButtonModel.propertyChange
Javadoc:
No Javadoc available
Method code:
public void propertyChange(PropertyChangeEvent e) {
setEnabled(((Action) e.getSource()).isEnabled());
}
No outgoing methods.
jfreerails.client.common.MappedButtonModel.setSelected
Javadoc:
No Javadoc available
Method code:
@Override
public void setSelected(boolean b) {
if (isSelected() != b) {
super.setSelected(b);
if (b) {
ActionAdapter.this.setSelectedItem(actionName);
}
}
}
Outgoing Methods (calls):
jfreerails.client.common.ModelRootImpl.addCompleteMoveReceiver
Javadoc:
No Javadoc available
Method code:
public void addCompleteMoveReceiver(MoveReceiver l) {
this.moveFork.addCompleteMoveReceiver(l);
}
Outgoing Methods (calls):
jfreerails.client.common.ModelRootImpl.addListListener
Javadoc:
No Javadoc available
Method code:
public void addListListener(WorldListListener listener) {
this.moveFork.addListListener(listener);
}
Outgoing Methods (calls):
jfreerails.client.common.ModelRootImpl.addMapListener
Javadoc:
No Javadoc available
Method code:
public void addMapListener(WorldMapListener l) {
this.moveFork.addMapListener(l);
}
Outgoing Methods (calls):
jfreerails.client.common.ModelRootImpl.addPropertyChangeListener
Javadoc:
No Javadoc available
Method code:
public void addPropertyChangeListener(ModelRootListener l) {
listeners.add(l);
}
No outgoing methods.
jfreerails.client.common.ModelRootImpl.addSplitMoveReceiver
Javadoc:
No Javadoc available
Method code:
public void addSplitMoveReceiver(MoveReceiver l) {
this.moveFork.addSplitMoveReceiver(l);
}
Outgoing Methods (calls):
jfreerails.client.common.ModelRootImpl.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(Move m) {
MoveStatus ms = this.moveReceiver.tryDoMove(m);
this.moveReceiver.processMove(m);
return ms;
}
Outgoing Methods (calls):
jfreerails.client.common.ModelRootImpl.doPreMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doPreMove(PreMove pm) {
Move m = pm.generateMove(world);
MoveStatus ms = moveReceiver.tryDoMove(m);
moveReceiver.processPreMove(pm);
return ms;
}
Outgoing Methods (calls):
jfreerails.client.common.ModelRootImpl.getPrincipal
Javadoc:
No Javadoc available
Method code:
public FreerailsPrincipal getPrincipal() {
if (null == playerPrincipal) {
throw new NullPointerException();
}
return playerPrincipal;
}
No outgoing methods.
jfreerails.client.common.ModelRootImpl.getProperty
Javadoc:
No Javadoc available
Method code:
public Object getProperty(Property p) {
return properties.get(p);
}
No outgoing methods.
jfreerails.client.common.ModelRootImpl.getWorld
Javadoc:
No Javadoc available
Method code:
public ReadOnlyWorld getWorld() {
return world;
}
No outgoing methods.
jfreerails.client.common.ModelRootImpl.is
Javadoc:
No Javadoc available
Method code:
public boolean is(ModelRoot.Property p, Object value) {
return getProperty(p).equals(value);
}
Outgoing Methods (calls):
jfreerails.client.common.ModelRootImpl.sendCommand
Javadoc:
No Javadoc available
Method code:
public void sendCommand(Message2Server c) {
if (null != serverCommandReceiver) {
serverCommandReceiver.sendCommand(c);
} else {
System.err.println(c.toString());
}
}
Outgoing Methods (calls):
jfreerails.client.common.ModelRootImpl.setMoveFork
Javadoc:
No Javadoc available
Method code:
public void setMoveFork(MoveChainFork moveFork) {
this.moveFork = moveFork;
}
No outgoing methods.
jfreerails.client.common.ModelRootImpl.setMoveReceiver
Javadoc:
No Javadoc available
Method code:
public void setMoveReceiver(UntriedMoveReceiver moveReceiver) {
this.moveReceiver = moveReceiver;
}
No outgoing methods.
jfreerails.client.common.ModelRootImpl.setProperty
Javadoc:
No Javadoc available
Method code:
public void setProperty(Property p, Object newValue) {
Object oldValue = properties.get(p);
properties.put(p, newValue);
for (ModelRootListener listener : listeners) {
listener.propertyChange(p, oldValue, newValue);
}
}
Outgoing Methods (calls):
jfreerails.client.common.ModelRootImpl.setServerCommandReceiver
Javadoc:
No Javadoc available
Method code:
public void setServerCommandReceiver(
ServerCommandReceiver serverCommandReceiver) {
this.serverCommandReceiver = serverCommandReceiver;
}
No outgoing methods.
jfreerails.client.common.ModelRootImpl.setup
Javadoc:
/** * Updates the ModelRoot with those properties which are dependent upon the * world model. Call this when the world model is changed (e.g. new map is * loaded) */
Method code:
/**
* Updates the ModelRoot with those properties which are dependent upon the
* world model. Call this when the world model is changed (e.g. new map is
* loaded)
*/
public void setup(ReadOnlyWorld world, FreerailsPrincipal p) {
this.world = world;
assert p != null;
assert world.isPlayer(p);
playerPrincipal = p;
if (null == world) {
throw new NullPointerException();
}
BuildTrackStrategy bts = BuildTrackStrategy.getDefault(world);
setProperty(ModelRoot.Property.BUILD_TRACK_STRATEGY, bts);
hasBeenSetup = true;
}
Outgoing Methods (calls):
jfreerails.client.common.ModelRootImpl.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(Move m) {
return this.moveReceiver.tryDoMove(m);
}
Outgoing Methods (calls):
jfreerails.client.common.ModelRootListener.propertyChange
Javadoc:
No Javadoc available
Method code:
void propertyChange(ModelRoot.Property p, Object oldValue, Object newValue);
No outgoing methods.
jfreerails.client.common.MyGlassPanel.formKeyPressed
Javadoc:
No Javadoc available
Method code:
// GEN-LAST:event_formMousePressed
private void formKeyPressed(java.awt.event.KeyEvent evt) { // GEN-FIRST:event_formKeyPressed
// Add your handling code here:
}
No outgoing methods.
jfreerails.client.common.MyGlassPanel.formMouseMoved
Javadoc:
No Javadoc available
Method code:
// GEN-END:initComponents
private void formMouseMoved(java.awt.event.MouseEvent evt) { // GEN-FIRST:event_formMouseMoved
// Add your handling code here:
}
No outgoing methods.
jfreerails.client.common.MyGlassPanel.formMousePressed
Javadoc:
No Javadoc available
Method code:
// GEN-LAST:event_formMouseMoved
private void formMousePressed(java.awt.event.MouseEvent evt) { // GEN-FIRST:event_formMousePressed
// Add your handling code here:
}
No outgoing methods.
jfreerails.client.common.MyGlassPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the FormEditor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() { // GEN-BEGIN:initComponents
contentPanel = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
java.awt.GridBagConstraints gridBagConstraints1;
setOpaque(false);
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mousePressed(java.awt.event.MouseEvent evt) {
formMousePressed(evt);
}
});
addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
@Override
public void mouseMoved(java.awt.event.MouseEvent evt) {
formMouseMoved(evt);
}
});
contentPanel.setPreferredSize(new java.awt.Dimension(60, 40));
contentPanel.setMinimumSize(new java.awt.Dimension(60, 40));
contentPanel.setBackground(java.awt.Color.red);
contentPanel.setMaximumSize(new java.awt.Dimension(60, 40));
gridBagConstraints1 = new java.awt.GridBagConstraints();
gridBagConstraints1.gridx = 2;
gridBagConstraints1.gridy = 1;
add(contentPanel, gridBagConstraints1);
}
Outgoing Methods (calls):
jfreerails.client.common.Painter.paint
Javadoc:
No Javadoc available
Method code:
void paint(Graphics2D g);
No outgoing methods.
jfreerails.client.common.RepaintManagerForActiveRendering.addDirtyRegion
Javadoc:
/** * Overrides the addDirtyRegion method to determine whether to add a dirty region * for repainting based on the component's ancestor hierarchy. If the component * has a different ancestor (as determined by {@link #hasDifferentAncestor(JComponent)}), * the superclass's method is called to add the dirty region. Otherwise, a repaint * request counter is incremented. * * @param c the component for which the dirty region is being added * @param x the x-coordinate of the top-left corner of the dirty region * @param y the y-coordinate of the top-left corner of the dirty region * @param w the width of the dirty region * @param h the height of the dirty region */
Method code:
@Override
public synchronized void addDirtyRegion(JComponent c, int x, int y, int w,
int h) {
if (hasDifferentAncestor(c)) {
super.addDirtyRegion(c, x, y, w, h);
} else {
numRepaintRequests++;
}
}
Outgoing Methods (calls):
jfreerails.client.common.RepaintManagerForActiveRendering.addInvalidComponent
Javadoc:
No Javadoc available
Method code:
@Override
public synchronized void addInvalidComponent(JComponent invalidComponent) {
if (hasDifferentAncestor(invalidComponent)) {
super.addInvalidComponent(invalidComponent);
} else {
numRepaintRequests++;
}
}
Outgoing Methods (calls):
jfreerails.client.common.RepaintManagerForActiveRendering.addJFrame
Javadoc:
No Javadoc available
Method code:
public static synchronized void addJFrame(JFrame f) {
activelyRenderedComponents.add(f);
}
No outgoing methods.
jfreerails.client.common.RepaintManagerForActiveRendering.getNumRepaintRequests
Javadoc:
No Javadoc available
Method code:
public static long getNumRepaintRequests() {
return numRepaintRequests;
}
No outgoing methods.
jfreerails.client.common.RepaintManagerForActiveRendering.hasDifferentAncestor
Javadoc:
No Javadoc available
Method code:
private boolean hasDifferentAncestor(JComponent aComponent) {
Container topLevelAncestor = aComponent.getTopLevelAncestor();
if (null == topLevelAncestor
|| activelyRenderedComponents.contains(topLevelAncestor)) {
return false;
}
return true;
}
No outgoing methods.
jfreerails.client.common.RepaintManagerForActiveRendering.markCompletelyClean
Javadoc:
No Javadoc available
Method code:
@Override
public void markCompletelyClean(JComponent aComponent) {
if (hasDifferentAncestor(aComponent)) {
super.markCompletelyClean(aComponent);
} else {
numRepaintRequests++;
}
}
Outgoing Methods (calls):
jfreerails.client.common.RepaintManagerForActiveRendering.markCompletelyDirty
Javadoc:
No Javadoc available
Method code:
@Override
public void markCompletelyDirty(JComponent aComponent) {
if (hasDifferentAncestor(aComponent)) {
super.markCompletelyDirty(aComponent);
} else {
numRepaintRequests++;
}
}
Outgoing Methods (calls):
jfreerails.client.common.RepaintManagerForActiveRendering.setAsCurrentManager
Javadoc:
No Javadoc available
Method code:
public static void setAsCurrentManager() {
RepaintManager.setCurrentManager(instance);
}
No outgoing methods.
jfreerails.client.common.SoundManager.addClip
Javadoc:
No Javadoc available
Method code:
public void addClip(String s) throws IOException,
UnsupportedAudioFileException, LineUnavailableException {
if (samples.containsKey(s)) {
return;
}
URL url = getClass().getResource(s);
AudioInputStream audioInputStream = AudioSystem
.getAudioInputStream(loadStream(url.openStream()));
Sample sample = new Sample();
sample.format = audioInputStream.getFormat();
sample.size = (int) (sample.format.getFrameSize() * audioInputStream
.getFrameLength());
sample.audio = new byte[sample.size];
sample.info = new DataLine.Info(Clip.class, sample.format, sample.size);
audioInputStream.read(sample.audio, 0, sample.size);
samples.put(s, sample);
}
Outgoing Methods (calls):
jfreerails.client.common.SoundManager.getSoundManager
Javadoc:
No Javadoc available
Method code:
public static SoundManager getSoundManager() {
return soundManager;
}
No outgoing methods.
jfreerails.client.common.SoundManager.loadStream
Javadoc:
No Javadoc available
Method code:
private ByteArrayInputStream loadStream(InputStream inputstream)
throws IOException {
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
for (int i = inputstream.read(data); i != -1; i = inputstream
.read(data)) {
bytearrayoutputstream.write(data, 0, i);
}
inputstream.close();
bytearrayoutputstream.close();
data = bytearrayoutputstream.toByteArray();
return new ByteArrayInputStream(data);
}
No outgoing methods.
jfreerails.client.common.SoundManager.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
SoundManager soundPlayer = getSoundManager();
for (int i = 0; i < 100; i++) {
soundPlayer.playSound("/jfreerails/client/sounds/cash.wav", 10);
try {
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Outgoing Methods (calls):
jfreerails.client.common.SoundManager.playSound
Javadoc:
No Javadoc available
Method code:
public void playSound(String s, int loops) {
if (playSounds) {
try {
if (!samples.containsKey(s)) {
addClip(s);
}
Sample sample = samples.get(s);
Clip clip;
if (voices.size() < maxLines) {
clip = (Clip) mixer.getLine(sample.info);
} else {
clip = voices.removeFirst();
clip.stop();
clip.flush();
clip.close();
}
clip.addLineListener(this);
clip.open(sample.format, sample.audio, 0, sample.size);
clip.loop(loops);
voices.add(clip);
} catch (LineUnavailableException e) {
logger.warning(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Outgoing Methods (calls):
jfreerails.client.common.SoundManager.propertyChange
Javadoc:
No Javadoc available
Method code:
public void propertyChange(ModelRoot.Property p, Object before, Object after) {
if (p.equals(ModelRoot.Property.PLAY_SOUNDS)) {
Boolean b = (Boolean) after;
playSounds = b.booleanValue();
}
}
No outgoing methods.
jfreerails.client.common.SoundManager.update
Javadoc:
No Javadoc available
Method code:
public void update(LineEvent event) {
// TODO free up resources when we have finished playing a clip.
}
No outgoing methods.
jfreerails.client.common.Unknown.processMove
Javadoc:
No Javadoc available
Method code:
public void processMove(Move Move) {
}
No outgoing methods.
jfreerails.client.common.Unknown.processPreMove
Javadoc:
No Javadoc available
Method code:
public void processPreMove(PreMove pm) {
}
No outgoing methods.
jfreerails.client.common.Unknown.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(Move move) {
return MoveStatus.moveFailed("No move receiver set on model root!");
}
Outgoing Methods (calls):
jfreerails.client.renderer.AbstractTileRenderer.checkTile
Javadoc:
No Javadoc available
Method code:
int checkTile(int x, int y, ReadOnlyWorld w) {
int match = 0;
if (((x < w.getMapWidth()) && (x >= 0)) && (y < w.getMapHeight())
&& (y >= 0)) {
for (int i = 0; i < typeNumbers.length; i++) {
TerrainTile tt = (TerrainTile) w.getTile(x, y);
if (tt.getTerrainTypeID() == typeNumbers[i]) {
match = 1;
// A match
}
}
} else {
match = 1; // A match
/*
* If the tile we are checking is off the map, let it be a match.
* This stops coast appearing where the ocean meets the map edge.
*/
}
return match;
}
Outgoing Methods (calls):
jfreerails.client.renderer.AbstractTileRenderer.dumpImages
Javadoc:
No Javadoc available
Method code:
abstract public void dumpImages(ImageManager imageManager);
No outgoing methods.
jfreerails.client.renderer.AbstractTileRenderer.generateFileNameNumber
Javadoc:
No Javadoc available
Method code:
protected abstract String generateFileNameNumber(int i);
No outgoing methods.
jfreerails.client.renderer.AbstractTileRenderer.generateRelativeFileName
Javadoc:
No Javadoc available
Method code:
String generateRelativeFileName(int i) {
return "terrain" + File.separator + this.getTerrainType() + "_"
+ generateFileNameNumber(i) + ".png";
}
Outgoing Methods (calls):
jfreerails.client.renderer.AbstractTileRenderer.getDefaultIcon
Javadoc:
No Javadoc available
Method code:
public Image getDefaultIcon() {
return getTileIcons()[0];
}
Outgoing Methods (calls):
jfreerails.client.renderer.AbstractTileRenderer.getIcon
Javadoc:
/** * Returns an icon for the tile at x,y, which may depend on the terrain * types of of the surrounding tiles. */
Method code:
/**
* Returns an icon for the tile at x,y, which may depend on the terrain
* types of of the surrounding tiles.
*/
Image getIcon(int x, int y, ReadOnlyWorld w) {
int tile = selectTileIcon(x, y, w);
if (getTileIcons()[tile] != null) {
return getTileIcons()[tile];
}
throw new NullPointerException("Error in TileView.getIcon: icon no. "
+ tile + "==null");
}
Outgoing Methods (calls):
jfreerails.client.renderer.AbstractTileRenderer.getTerrainType
Javadoc:
No Javadoc available
Method code:
String getTerrainType() {
return tileModel.getTerrainTypeName();
}
Outgoing Methods (calls):
jfreerails.client.renderer.AbstractTileRenderer.getTileIcons
Javadoc:
No Javadoc available
Method code:
Image[] getTileIcons() {
return tileIcons;
}
No outgoing methods.
jfreerails.client.renderer.AbstractTileRenderer.renderTile
Javadoc:
No Javadoc available
Method code:
public void renderTile(java.awt.Graphics g, int screenX, int screenY,
int mapX, int mapY, ReadOnlyWorld w) {
Image icon = this.getIcon(mapX, mapY, w);
if (null != icon) {
g.drawImage(icon, screenX, screenY, null);
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.AbstractTileRenderer.selectTileIcon
Javadoc:
No Javadoc available
Method code:
int selectTileIcon(int x, int y, ReadOnlyWorld w) {
return 0;
}
No outgoing methods.
jfreerails.client.renderer.AbstractTileRenderer.setTileIcons
Javadoc:
No Javadoc available
Method code:
void setTileIcons(Image[] tileIcons) {
this.tileIcons = tileIcons;
}
No outgoing methods.
jfreerails.client.renderer.BlankMapRenderer.getMapSizeInPixels
Javadoc:
No Javadoc available
Method code:
public Dimension getMapSizeInPixels() {
int height = (int) (400 * scale);
int width = (int) (400 * scale);
return new Dimension(height, width);
}
No outgoing methods.
jfreerails.client.renderer.BlankMapRenderer.getScale
Javadoc:
No Javadoc available
Method code:
public float getScale() {
return scale;
}
No outgoing methods.
jfreerails.client.renderer.BlankMapRenderer.paintRect
Javadoc:
No Javadoc available
Method code:
public void paintRect(Graphics g, Rectangle visibleRect) {
g.setColor(Color.darkGray);
g.fillRect(0, 0, (int) (scale * 400), (int) (scale * 400));
g.setColor(Color.blue);
int x = (int) (100 * scale);
int y = (int) (100 * scale);
int height = (int) (200 * scale);
int width = (int) (200 * scale);
g.fillRect(x, y, height, width);
}
No outgoing methods.
jfreerails.client.renderer.BlankMapRenderer.paintTile
Javadoc:
/** * Paints a single tile at the specified tile coordinates using the provided graphics context. * This method delegates the painting operation to {@link #paintRect(Graphics, java.awt.Shape)} * by passing {@code null} as the shape parameter, which likely results in default rendering behavior. * * @param g the graphics context used for rendering * @param tileX the x-coordinate of the tile to paint * @param tileY the y-coordinate of the tile to paint */
Method code:
public void paintTile(Graphics g, int tileX, int tileY) {
paintRect(g, null);
}
Outgoing Methods (calls):
jfreerails.client.renderer.BlankMapRenderer.refreshAll
Javadoc:
No Javadoc available
Method code:
public void refreshAll() {
// do nothing
}
No outgoing methods.
jfreerails.client.renderer.BlankMapRenderer.refreshTile
Javadoc:
No Javadoc available
Method code:
public void refreshTile(int x, int y) {
}
No outgoing methods.
jfreerails.client.renderer.BufferedTiledBackgroundRenderer.paintBufferRectangle
Javadoc:
No Javadoc available
Method code:
protected abstract void paintBufferRectangle(int x, int y, int width,
int height);
No outgoing methods.
jfreerails.client.renderer.BufferedTiledBackgroundRenderer.paintRect
Javadoc:
/** * Updates the backbuffer as necessary, then draws it on to the Graphics * object passed. * * @param outputGraphics * Once it has been updated, the backbuffer is drawn onto this * Graphics object. * @param newVisibleRectangle * The region of the map that the backbuffer must be updated to * display. */
Method code:
/**
* Updates the backbuffer as necessary, then draws it on to the Graphics
* object passed.
*
* @param outputGraphics
* Once it has been updated, the backbuffer is drawn onto this
* Graphics object.
* @param newVisibleRectangle
* The region of the map that the backbuffer must be updated to
* display.
*/
public void paintRect(Graphics outputGraphics,
Rectangle newVisibleRectangle) {
do {
/*
* If this is the first call to the paint method or the component
* has just been resized, we need to create a new backgroundBuffer.
*/
if ((backgroundBuffer == null)
|| (newVisibleRectangle.height != bufferRect.height)
|| (newVisibleRectangle.width != bufferRect.width)) {
setbackgroundBuffer(newVisibleRectangle.width,
newVisibleRectangle.height);
}
// Test if image is lost and restore it.
int valCode = backgroundBuffer.validate(defaultConfig);
if (valCode == VolatileImage.IMAGE_INCOMPATIBLE) {
setbackgroundBuffer(newVisibleRectangle.width,
newVisibleRectangle.height);
} else if (valCode == VolatileImage.IMAGE_RESTORED) {
resetGraphics();
this.refreshBackground();
}
/*
* Has the VisibleRectangle moved since the last paint?
*/
if ((bufferRect.x != newVisibleRectangle.x)
|| (bufferRect.y != newVisibleRectangle.y)) {
int dx = bufferRect.x - newVisibleRectangle.x;
int dy = bufferRect.y - newVisibleRectangle.y;
scrollbackgroundBuffer(dx, dy);
bufferRect.setBounds(newVisibleRectangle);
}
if ((bufferRect.width != newVisibleRectangle.width)
&& (bufferRect.height != newVisibleRectangle.height)) {
paintBufferRectangle(newVisibleRectangle.x - bufferRect.x,
newVisibleRectangle.y - bufferRect.y,
newVisibleRectangle.width,
newVisibleRectangle.height);
}
outputGraphics.drawImage(backgroundBuffer,
newVisibleRectangle.x, newVisibleRectangle.y, null);
bufferRect.setBounds(newVisibleRectangle);
} while (backgroundBuffer.contentsLost());
}
Outgoing Methods (calls):
jfreerails.client.renderer.BufferedTiledBackgroundRenderer.refreshAll
Javadoc:
No Javadoc available
Method code:
public void refreshAll() {
refreshBackground();
}
Outgoing Methods (calls):
jfreerails.client.renderer.BufferedTiledBackgroundRenderer.refreshBackground
Javadoc:
No Javadoc available
Method code:
private void refreshBackground() {
paintBufferRectangle(0, 0, bufferRect.width, bufferRect.height);
}
Outgoing Methods (calls):
jfreerails.client.renderer.BufferedTiledBackgroundRenderer.resetGraphics
Javadoc:
/** When the VolatileImage is created or restored, we need to (re)create the Graphics objects. */
Method code:
/** When the VolatileImage is created or restored, we need to (re)create the
Graphics objects.
*/
private void resetGraphics() {
if (bg != null) {
bg.dispose();
}
bg = backgroundBuffer.getGraphics();
if (translatedBg != null) {
translatedBg.dispose();
}
translatedBg = bg.create();
translatedBg.translate(-bufferRect.x, -bufferRect.y);
}
No outgoing methods.
jfreerails.client.renderer.BufferedTiledBackgroundRenderer.scrollbackgroundBuffer
Javadoc:
No Javadoc available
Method code:
private void scrollbackgroundBuffer(int dx, int dy) {
int copyWidth = bufferRect.width;
int copyHeight = bufferRect.height;
int copySourceX = 0;
int copySourceY = 0;
if (dx > 0) {
copyWidth -= dx;
} else {
copyWidth += dx;
copySourceX = -dx;
}
if (dy > 0) {
copyHeight -= dy;
} else {
copyHeight += dy;
copySourceY = -dy;
}
bg.copyArea(copySourceX, copySourceY, copyWidth, copyHeight, dx, dy);
bufferRect.x -= dx;
bufferRect.y -= dy;
// paint exposed areas
if (dx != 0) {
if (dx > 0) {
bg.setClip(0, 0, dx, bufferRect.height);
bg.clearRect(0, 0, dx, bufferRect.height);
paintBufferRectangle(0, 0, dx, bufferRect.height);
} else {
bg.setClip(bufferRect.width + dx, 0, -dx, bufferRect.height);
bg.clearRect(bufferRect.width + dx, 0, -dx, bufferRect.height);
paintBufferRectangle(bufferRect.width + dx, 0, -dx,
bufferRect.height);
}
}
if (dy != 0) {
if (dy > 0) {
bg.setClip(0, 0, bufferRect.width, dy);
bg.clearRect(0, 0, bufferRect.width, dy);
paintBufferRectangle(0, 0, bufferRect.width, dy);
} else {
bg.setClip(0, bufferRect.height + dy, bufferRect.width, -dy);
bg.clearRect(0, bufferRect.height + dy, bufferRect.width, -dy);
paintBufferRectangle(0, bufferRect.height + dy,
bufferRect.width, -dy);
}
}
bg.setClip(0, 0, bufferRect.width, bufferRect.height);
}
Outgoing Methods (calls):
jfreerails.client.renderer.BufferedTiledBackgroundRenderer.setbackgroundBuffer
Javadoc:
No Javadoc available
Method code:
private void setbackgroundBuffer(int w, int h) {
// Releases VRAM used by backgroundBuffer.
if (backgroundBuffer != null) {
backgroundBuffer.flush();
}
// Create new backgroundBuffer.
backgroundBuffer = defaultConfig.createCompatibleVolatileImage(w, h);
bufferRect.height = backgroundBuffer.getHeight(null);
bufferRect.width = backgroundBuffer.getWidth(null);
resetGraphics();
bg.clearRect(0, 0, w, h);
refreshBackground();
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.getBts
Javadoc:
/** Utility method that gets the BuildTrackStrategy from the model root. */
Method code:
/** Utility method that gets the BuildTrackStrategy from the model root. */
private BuildTrackStrategy getBts() {
BuildTrackStrategy btss = (BuildTrackStrategy) modelRoot
.getProperty(ModelRoot.Property.BUILD_TRACK_STRATEGY);
if (null == btss)
throw new NullPointerException();
return btss;
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.getBuildMode
Javadoc:
No Javadoc available
Method code:
private TrackMoveProducer.BuildMode getBuildMode() {
TrackMoveProducer.BuildMode mode;
mode = (TrackMoveProducer.BuildMode) modelRoot
.getProperty(ModelRoot.Property.TRACK_BUILDER_MODE);
return mode;
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.getCursorPosition
Javadoc:
/** Utility method that gets the cursor position from the model root. */
Method code:
/** Utility method that gets the cursor position from the model root. */
private ImPoint getCursorPosition() {
ImPoint point = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.CURSOR_POSITION);
// Check for null & make a defensive copy
point = null == point ? new ImPoint() : point;
if (!modelRoot.getWorld().boundsContain(point.x, point.y)) {
throw new IllegalStateException(String.valueOf(point));
}
return point;
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.hide
Javadoc:
/** Hides and cancels any proposed track. */
Method code:
/** Hides and cancels any proposed track. */
public void hide() {
this.setVisible(false);
setTargetPoint(null);
reset();
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.isBuildTrackSuccessful
Javadoc:
/** Returns true if all the track pieces can be successfully built. */
Method code:
/** Returns true if all the track pieces can be successfully built. */
public boolean isBuildTrackSuccessful() {
return isBuildTrackSuccessful;
}
No outgoing methods.
jfreerails.client.renderer.BuildTrackController.isBuilding
Javadoc:
/** * returns <code>true</code> if the track is being build - it is iff the * build track is shown * * @return boolean */
Method code:
/**
* returns <code>true</code> if the track is being build - it is iff the
* build track is shown
*
* @return boolean
*/
public boolean isBuilding() {
return visible;
}
No outgoing methods.
jfreerails.client.renderer.BuildTrackController.moveCursorMoreTiles
Javadoc:
/** * uses <code>trackBuilder</code> if not null -- otherwise uses own * <code>buildTrack</code> method - that is applied on * <code>worldDifferences</code> * * @param track * List * @param trackBuilder * TrackMoveProducer */
Method code:
/**
* uses <code>trackBuilder</code> if not null -- otherwise uses own
* <code>buildTrack</code> method - that is applied on
* <code>worldDifferences</code>
*
* @param track
* List
* @param trackBuilder
* TrackMoveProducer
*/
private MoveStatus moveCursorMoreTiles(List<ImPoint> track,
TrackMoveProducer trackBuilder) {
ImPoint oldPosition = getCursorPosition();
if(!Step.checkValidity(oldPosition, track.get(0))){
throw new IllegalStateException(oldPosition.toString()+ " and "+track.get(0).toString());
}
MoveStatus ms = null;
int piecesOfNewTrack = 0;
if (null != trackBuilder) {
trackBuilder.setBuildTrackStrategy(getBts());
}
for (Iterator<ImPoint> iter = track.iterator(); iter.hasNext();) {
ImPoint point = iter.next();
LOGGER.fine("point" + point);
LOGGER.fine("oldPosition" + oldPosition);
if (oldPosition.equals(point)) {
LOGGER.fine("(oldPosition.equals(point))" + point);
continue;
}
Step vector = Step.getInstance(point.x - oldPosition.x, point.y
- oldPosition.y);
// If there is already track between the two tiles, do nothing
FreerailsTile tile = (FreerailsTile) realWorld.getTile(
oldPosition.x, oldPosition.y);
if (tile.getTrackPiece().getTrackConfiguration().contains(vector)) {
oldPosition = point;
continue;
}
piecesOfNewTrack++;
if (trackBuilder != null) {
ms = trackBuilder.buildTrack(oldPosition, vector);
} else {
ms = planBuildingTrack(oldPosition, vector);
}
if (ms.ok) {
setCursorMessage("");
} else {
setCursorMessage(ms.message);
reset();
return ms;
}
oldPosition = point;
}
/* Check whether there is already track at every point. */
if (piecesOfNewTrack == 0) {
MoveStatus moveFailed = MoveStatus.moveFailed("Track already here");
setCursorMessage(moveFailed.message);
return moveFailed;
}
isBuildTrackSuccessful = true;
// If track has actually been built, play the build track sound.
if (trackBuilder != null && ms.isOk()) {
if (trackBuilder.getTrackBuilderMode() == BUILD_TRACK) {
this.soundManager.playSound(
"/jfreerails/client/sounds/buildtrack.wav", 0);
}
}
return ms;
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.planBuildingTrack
Javadoc:
/** * Attempts to building track from the specified point in the specified * direction on the worldDiff object. */
Method code:
/**
* Attempts to building track from the specified point in the specified
* direction on the worldDiff object.
*/
private MoveStatus planBuildingTrack(ImPoint point, Step vector) {
FreerailsTile tileA = (FreerailsTile) worldDiffs.getTile(point.x,
point.y);
BuildTrackStrategy bts = getBts();
int trackTypeAID = bts.getRule(tileA.getTerrainTypeID());
TrackRule trackRuleA = (TrackRule) worldDiffs.get(SKEY.TRACK_RULES,
trackTypeAID);
FreerailsTile tileB = (FreerailsTile) worldDiffs.getTile(point.x
+ vector.deltaX, point.y + vector.deltaY);
int trackTypeBID = bts.getRule(tileB.getTerrainTypeID());
TrackRule trackRuleB = (TrackRule) worldDiffs.get(SKEY.TRACK_RULES,
trackTypeBID);
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(point, vector, trackRuleA, trackRuleB,
worldDiffs, principal);
return move.doMove(worldDiffs, principal);
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.reset
Javadoc:
/** Cancels any proposed track and resets the path finder. */
Method code:
/** Cancels any proposed track and resets the path finder. */
private void reset() {
worldDiffs.reset();
path4newTrackFinder.abandonSearch();
this.builtTrack.clear();
this.isBuildTrackSuccessful = false;
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.searchStatus
Javadoc:
No Javadoc available
Method code:
int searchStatus() {
if (buildNewTrack) {
return path4newTrackFinder.getStatus();
}
return pathOnExistingTrackFinder.getStatus();
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.setCursorMessage
Javadoc:
/** Utility method that sets the CURSOR_MESSAGE property on the model root. */
Method code:
/** Utility method that sets the CURSOR_MESSAGE property on the model root. */
private void setCursorMessage(String s) {
modelRoot.setProperty(ModelRoot.Property.CURSOR_MESSAGE, s);
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.setProposedTrack
Javadoc:
/** Sets the proposed track: from the current cursor position to the specified point.*/
Method code:
/** Sets the proposed track: from the current cursor position to the specified point.*/
public void setProposedTrack(ImPoint to,
TrackMoveProducer trackBuilder) {
ImPoint from = getCursorPosition();
assert (trackBuilder.getTrackBuilderMode() != IGNORE_TRACK);
assert (trackBuilder.getTrackBuilderMode() != BUILD_STATION);
buildNewTrack = trackBuilder.getTrackBuilderMode() == BUILD_TRACK;
/*
* If we have just found the route between the two points, don't waste
* time doing it again.
*/
if (null != targetPoint && null != startPoint
&& targetPoint.equals(to)
&& startPoint.equals(from)
&& searchStatus() != IncrementalPathFinder.SEARCH_NOT_STARTED) {
return;
}
worldDiffs.reset();
builtTrack.clear();
isBuildTrackSuccessful = false;
if (from.equals(to)) {
hide();
return;
}
/* Check both points are on the map. */
if (!realWorld.boundsContain(from.x, from.y)
|| !realWorld.boundsContain(to.x, to.y)) {
hide();
return;
}
setTargetPoint(to);
startPoint = from;
try {
BuildTrackStrategy bts = getBts();
if (buildNewTrack) {
path4newTrackFinder.setupSearch(from, to, bts);
} else {
pathOnExistingTrackFinder.setupSearch(from, to);
}
} catch (PathNotFoundException e) {
setCursorMessage(e.getMessage());
return;
}
updateSearch();
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.setTargetPoint
Javadoc:
/** * @param newTargetPoint * The m_targetPoint to set. */
Method code:
/**
* @param newTargetPoint
* The m_targetPoint to set.
*/
private void setTargetPoint(ImPoint newTargetPoint) {
this.targetPoint = newTargetPoint;
ImPoint p = null == newTargetPoint ? null : newTargetPoint;
modelRoot.setProperty(ModelRoot.Property.THINKING_POINT, p);
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.setVisible
Javadoc:
No Javadoc available
Method code:
private void setVisible(boolean show) {
if (show == visible) {
return;
}
if (show) {
setWorldDiffs(worldDiffs);
} else {
setWorldDiffs(null);
}
this.visible = show;
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.setWorldDiffs
Javadoc:
No Javadoc available
Method code:
private void setWorldDiffs(WorldDiffs worldDiffs) {
modelRoot.setProperty(ModelRoot.Property.PROPOSED_TRACK, worldDiffs);
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.show
Javadoc:
No Javadoc available
Method code:
public void show() {
this.setVisible(true);
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.update
Javadoc:
No Javadoc available
Method code:
public void update() {
// update search for path if necessary.
if (searchStatus() == IncrementalPathFinder.SEARCH_PAUSED) {
updateSearch();
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.updateSearch
Javadoc:
/** * Updates the search, if the search is completed, the proposed track is * shown. */
Method code:
/**
* Updates the search, if the search is completed, the proposed track is
* shown.
*/
private void updateSearch() {
try {
if (buildNewTrack) {
path4newTrackFinder.search(100);
} else {
pathOnExistingTrackFinder.search(100);
}
} catch (PathNotFoundException e) {
setCursorMessage(e.getMessage());
return;
}
if (searchStatus() == IncrementalPathFinder.PATH_FOUND) {
if (buildNewTrack) {
builtTrack = path4newTrackFinder.pathAsPoints();
moveCursorMoreTiles(builtTrack);
} else {
boolean okSoFar = true;
path = pathOnExistingTrackFinder.pathAsVectors();
TrackMoveProducer.BuildMode mode = getBuildMode();
int locationX = startPoint.x;
int locationY = startPoint.y;
FreerailsPrincipal fp = modelRoot.getPrincipal();
for (Step v : path) {
Move move;
attemptMove: {
switch (mode) {
case REMOVE_TRACK:
try {
move = ChangeTrackPieceCompositeMove
.generateRemoveTrackMove(new ImPoint(
locationX, locationY), v,
worldDiffs, fp);
break;
} catch (Exception e1) {
e1.printStackTrace();
break attemptMove;
}
case UPGRADE_TRACK:
int owner = ChangeTrackPieceCompositeMove.getOwner(
fp, worldDiffs);
FreerailsTile tile = (FreerailsTile) worldDiffs
.getTile(locationX, locationY);
int tt = tile.getTerrainTypeID();
int trackRuleID = getBts().getRule(tt);
/*
* Skip tiles that already have the right track
* type.
*/
if (trackRuleID == tile.getTrackPiece().getTrackTypeID()) {
break attemptMove;
}
TrackRule trackRule = (TrackRule) worldDiffs.get(
SKEY.TRACK_RULES, trackRuleID);
TrackPiece after = new TrackPieceImpl(tile
.getTrackPiece().getTrackConfiguration(), trackRule, owner,
trackRuleID);
/*
* We don't want to 'upgrade' a station to track.
* See bug 874416.
*/
if (tile.getTrackPiece().getTrackRule().isStation()) {
break attemptMove;
}
move = UpgradeTrackMove.generateMove(tile
.getTrackPiece(), after, new ImPoint(
locationX, locationY));
break;
default:
throw new IllegalStateException(mode.toString());
}// end of switch statement
MoveStatus ms = move.doMove(worldDiffs, fp);
okSoFar = ms.ok && okSoFar;
}// end of attemptMove
locationX += v.deltaX;
locationY += v.deltaY;
}// end for loop
startPoint = new ImPoint(locationX, locationY);
isBuildTrackSuccessful = okSoFar;
if (okSoFar) {
setCursorMessage("");
}
}
show();
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.updateUntilComplete
Javadoc:
No Javadoc available
Method code:
public void updateUntilComplete() {
while (searchStatus() != IncrementalPathFinder.PATH_FOUND) {
updateSearch();
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackController.updateWorld
Javadoc:
/** * Saves track into real world */
Method code:
/**
* Saves track into real world
*/
public ImPoint updateWorld(TrackMoveProducer trackBuilder) {
ImPoint actPoint = getCursorPosition();
if (buildNewTrack) {
if (builtTrack.size() > 0) {
MoveStatus ms = moveCursorMoreTiles(builtTrack, trackBuilder);
/* Note, reset() will have been called if ms.ok == false */
if (ms.ok) {
actPoint = builtTrack.get(builtTrack.size() - 1);
builtTrack = new ArrayList<ImPoint>();
}
}
} else {
trackBuilder.setBuildTrackStrategy(getBts());
MoveStatus ms = trackBuilder.buildTrack(actPoint, path);
//MoveStatus ms = trackBuilder.buildTrack(startPoint, path);
if (ms.ok) {
actPoint = targetPoint;
setCursorMessage("");
if (REMOVE_TRACK == getBuildMode()) {
soundManager.playSound(
"/jfreerails/client/sounds/removetrack.wav", 0);
} else {
soundManager.playSound(
"/jfreerails/client/sounds/buildtrack.wav", 0);
}
} else {
setCursorMessage(ms.message);
reset();
}
}
hide();
return actPoint;
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackControllerTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
w = MapFixtureFactory2.getCopy();
modelRoot = new ModelRootImpl();
FreerailsPrincipal p = w.getPlayer(0).getPrincipal();
modelRoot.setup(w, p);
buildTrackController = new BuildTrackController(w, modelRoot);
MoveExecutor executor = new SimpleMoveExecutor(w, 0);
trackBuilder = new TrackMoveProducer(executor, w, modelRoot);
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
final Integer ruleID = new Integer(i);
TrackRule rule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
if (rule.getTypeName().equals("standard track")) {
singleTrackRuleID = ruleID;
}
if (rule.getTypeName().equals("double track")) {
doubleTrackRuleID = ruleID;
}
}
assertFalse(singleTrackRuleID == -1);
assertFalse(doubleTrackRuleID == -1);
// unit tests should be silent!
modelRoot.setProperty(Property.PLAY_SOUNDS, false);
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackControllerTest.testBuildTrack
Javadoc:
No Javadoc available
Method code:
public void testBuildTrack() {
ImPoint from = new ImPoint(10, 10);
modelRoot.setProperty(Property.CURSOR_POSITION, from);
ImPoint to = new ImPoint(20, 10);
buildTrackController.setProposedTrack(to, trackBuilder);
buildTrackController.updateUntilComplete();
assertTrue(buildTrackController.isBuildTrackSuccessful());
// See if any track has actually been built.
FreerailsTile tile = (FreerailsTile) w.getTile(10, 10);
assertFalse(tile.hasTrack());
buildTrackController.updateWorld(trackBuilder);
tile = (FreerailsTile) w.getTile(10, 10);
assertTrue(tile.hasTrack());
tile = (FreerailsTile) w.getTile(20, 10);
assertTrue(tile.hasTrack());
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackControllerTest.testRemoveTrack
Javadoc:
No Javadoc available
Method code:
public void testRemoveTrack() {
// Build the track.
testBuildTrack();
// Then remove some of it.
trackBuilder.setTrackBuilderMode(BuildMode.REMOVE_TRACK);
ImPoint from = new ImPoint(15, 10);
modelRoot.setProperty(Property.CURSOR_POSITION, from);
ImPoint to = new ImPoint(20, 10);
buildTrackController.setProposedTrack(to, trackBuilder);
buildTrackController.updateUntilComplete();
assertTrue(buildTrackController.isBuildTrackSuccessful());
buildTrackController.updateWorld(trackBuilder);
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackControllerTest.testUpgradeTrack
Javadoc:
No Javadoc available
Method code:
public void testUpgradeTrack() {
// Build the track.
testBuildTrack();
// Change the strategy.
BuildTrackStrategy bts = BuildTrackStrategy.getSingleRuleInstance(
doubleTrackRuleID, modelRoot.getWorld());
trackBuilder.setBuildTrackStrategy(bts);
trackBuilder.setTrackBuilderMode(BuildMode.UPGRADE_TRACK);
// Upgrade part of the track.
modelRoot.setProperty(Property.CURSOR_POSITION, new ImPoint(15, 10));
buildTrackController
.setProposedTrack(new ImPoint(20, 10), trackBuilder);
buildTrackController.updateUntilComplete();
assertTrue(buildTrackController.isBuildTrackSuccessful());
buildTrackController.updateWorld(trackBuilder);
FreerailsTile tile = (FreerailsTile) w.getTile(10, 10);
assertEquals(singleTrackRuleID, tile.getTrackPiece().getTrackTypeID());
tile = (FreerailsTile) w.getTile(15, 10);
assertEquals(doubleTrackRuleID, tile.getTrackPiece().getTrackTypeID());
tile = (FreerailsTile) w.getTile(17, 10);
assertEquals(doubleTrackRuleID, tile.getTrackPiece().getTrackTypeID());
tile = (FreerailsTile) w.getTile(20, 10);
assertEquals(doubleTrackRuleID, tile.getTrackPiece().getTrackTypeID());
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackRenderer.getWorldDiffs
Javadoc:
No Javadoc available
Method code:
private WorldDiffs getWorldDiffs() {
if (modelRoot == null) {
return null;
}
return (WorldDiffs) modelRoot
.getProperty(ModelRoot.Property.PROPOSED_TRACK);
}
Outgoing Methods (calls):
jfreerails.client.renderer.BuildTrackRenderer.paint
Javadoc:
/** * Paints the proposed track and dots to distinguish the proposed track from * any existing track. */
Method code:
/**
* Paints the proposed track and dots to distinguish the proposed track from
* any existing track.
*/
public void paint(Graphics2D g) {
WorldDiffs worldDiffs = getWorldDiffs();
if (null != worldDiffs) {
for (Iterator<ImPoint> iter = worldDiffs.getMapDiffs(); iter
.hasNext();) {
ImPoint point = iter.next();
FreerailsTile fp = (FreerailsTile)worldDiffs.getTile(point.x,
point.y);
TrackPiece tp = fp.getTrackPiece();
int graphicsNumber = tp.getTrackGraphicID();
int ruleNumber = tp.getTrackTypeID();
jfreerails.client.renderer.TrackPieceRenderer trackPieceView = rr
.getTrackPieceView(ruleNumber);
trackPieceView.drawTrackPieceIcon(graphicsNumber, g, point.x,
point.y, tileSize);
}
ReadOnlyWorld realWorld = modelRoot.getWorld();
/*
* Draw small dots for each tile whose track has changed. The dots
* are white if track has been added or upgraded and red if it has
* been removed.
*/
for (Iterator<ImPoint> iter = worldDiffs.getMapDiffs(); iter
.hasNext();) {
ImPoint p = iter.next();
int x = p.x * tileSize.width
+ (tileSize.width - SMALL_DOT_WIDTH) / 2;
int y = p.y * tileSize.width
+ (tileSize.height - SMALL_DOT_WIDTH) / 2;
FreerailsTile before = (FreerailsTile) realWorld.getTile(p.x,
p.y);
FreerailsTile after = (FreerailsTile) worldDiffs.getTile(p.x,
p.y);
boolean trackRemoved = !after.getTrackPiece().getTrackConfiguration().contains(
before.getTrackPiece().getTrackConfiguration());
Color dotColor = trackRemoved ? Color.RED : Color.WHITE;
g.setColor(dotColor);
g.fillOval(x, y, SMALL_DOT_WIDTH, SMALL_DOT_WIDTH);
}
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.ChequeredTileRenderer.dumpImages
Javadoc:
No Javadoc available
Method code:
@Override
public void dumpImages(ImageManager imageManager) {
for (int i = 0; i < this.getTileIcons().length; i++) {
String fileName = generateRelativeFileName(i);
imageManager.setImage(fileName, this.getTileIcons()[i]);
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.ChequeredTileRenderer.generateFileNameNumber
Javadoc:
No Javadoc available
Method code:
@Override
protected String generateFileNameNumber(int i) {
return String.valueOf(i);
}
No outgoing methods.
jfreerails.client.renderer.ChequeredTileRenderer.selectTileIcon
Javadoc:
No Javadoc available
Method code:
@Override
public int selectTileIcon(int x, int y, ReadOnlyWorld w) {
return (x + y) % 2;
}
No outgoing methods.
jfreerails.client.renderer.CityNamesRenderer.paint
Javadoc:
No Javadoc available
Method code:
public void paint(Graphics2D g) {
g.setColor(Color.WHITE);
g.setFont(new Font("Arial", 0, 20));
// draw city names onto map
for (int i = 0; i < w.size(SKEY.CITIES); i++) {
CityModel tempCity = (CityModel) w.get(SKEY.CITIES, i);
g.drawString(tempCity.getCityName(), tempCity.getCityX() * 30,
tempCity.getCityY() * 30 + 10);
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.ForestStyleTileRenderer.dumpImages
Javadoc:
No Javadoc available
Method code:
@Override
public void dumpImages(ImageManager imageManager) {
for (int i = 0; i < this.getTileIcons().length; i++) {
String fileName = generateRelativeFileName(i);
imageManager.setImage(fileName, this.getTileIcons()[i]);
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.ForestStyleTileRenderer.generateFileNameNumber
Javadoc:
No Javadoc available
Method code:
@Override
protected String generateFileNameNumber(int i) {
return BinaryNumberFormatter.format(i, 2);
}
Outgoing Methods (calls):
jfreerails.client.renderer.ForestStyleTileRenderer.selectTileIcon
Javadoc:
No Javadoc available
Method code:
@Override
public int selectTileIcon(int x, int y, ReadOnlyWorld w) {
int iconNumber = 0;
for (int i = 0; i < 2; i++) {
iconNumber = iconNumber
| checkTile(x + X_LOOK_AT[i], y + Y_LOOK_AT[i], w);
iconNumber = iconNumber << 1;
}
iconNumber = iconNumber >> 1;
return iconNumber;
}
Outgoing Methods (calls):
jfreerails.client.renderer.MapBackgroundRender.paintRect
Javadoc:
No Javadoc available
Method code:
public void paintRect(Graphics g, Rectangle visibleRect) {
int tileWidth = 30;
int tileHeight = 30;
clipRectangle = g.getClipBounds(clipRectangle);
int x = clipRectangle.x / tileWidth;
int y = clipRectangle.y / tileHeight;
int width = (clipRectangle.width / tileWidth) + 2;
int height = (clipRectangle.height) / tileHeight + 2;
paintRectangleOfTiles(g, x, y, width, height);
cityNames.paint((Graphics2D) g);
stationNames.paint((Graphics2D) g);
}
Outgoing Methods (calls):
jfreerails.client.renderer.MapBackgroundRender.paintRectangleOfTiles
Javadoc:
No Javadoc available
Method code:
private void paintRectangleOfTiles(Graphics g, int x, int y, int width,
int height) {
terrainLayer.paintRectangleOfTiles(g, x, y, width, height);
trackLayer.paintRectangleOfTiles(g, x, y, width, height);
cityNames.paint((Graphics2D) g);
stationNames.paint((Graphics2D) g);
}
Outgoing Methods (calls):
jfreerails.client.renderer.MapBackgroundRender.paintTile
Javadoc:
No Javadoc available
Method code:
public void paintTile(Graphics g, int x, int y) {
terrainLayer.paintTile(g, x, y);
trackLayer.paintTile(g, x, y);
cityNames.paint((Graphics2D) g);
stationNames.paint((Graphics2D) g);
}
Outgoing Methods (calls):
jfreerails.client.renderer.MapBackgroundRender.refreshAll
Javadoc:
No Javadoc available
Method code:
public void refreshAll() {
// Do nothing
}
No outgoing methods.
jfreerails.client.renderer.MapBackgroundRender.refreshTile
Javadoc:
No Javadoc available
Method code:
public void refreshTile(int x, int y) {
// Do nothing
}
No outgoing methods.
jfreerails.client.renderer.MapLayerRenderer.paintRect
Javadoc:
No Javadoc available
Method code:
void paintRect(Graphics g, Rectangle visibleRect);
No outgoing methods.
jfreerails.client.renderer.MapLayerRenderer.paintTile
Javadoc:
No Javadoc available
Method code:
void paintTile(Graphics g, int tileX, int tileY);
No outgoing methods.
jfreerails.client.renderer.MapLayerRenderer.refreshAll
Javadoc:
No Javadoc available
Method code:
void refreshAll();
No outgoing methods.
jfreerails.client.renderer.MapLayerRenderer.refreshTile
Javadoc:
No Javadoc available
Method code:
void refreshTile(int x, int y);
No outgoing methods.
jfreerails.client.renderer.MapRenderer.getMapSizeInPixels
Javadoc:
No Javadoc available
Method code:
Dimension getMapSizeInPixels();
No outgoing methods.
jfreerails.client.renderer.MapRenderer.getScale
Javadoc:
No Javadoc available
Method code:
float getScale();
No outgoing methods.
jfreerails.client.renderer.MyRenderersRoot.getEngineImages
Javadoc:
No Javadoc available
Method code:
@Override
public TrainImages getEngineImages(int type) {
return this.trainImages;
}
No outgoing methods.
jfreerails.client.renderer.MyRenderersRoot.getImage
Javadoc:
No Javadoc available
Method code:
@Override
public Image getImage(String relativeFilename) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
No outgoing methods.
jfreerails.client.renderer.MyRenderersRoot.getScaledImage
Javadoc:
No Javadoc available
Method code:
@Override
public Image getScaledImage(String relativeFilename, int height) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
No outgoing methods.
jfreerails.client.renderer.MyRenderersRoot.getTileViewWithNumber
Javadoc:
No Javadoc available
Method code:
@Override
public TileRenderer getTileViewWithNumber(int i) {
throw new UnsupportedOperationException("Not supported yet.");
}
No outgoing methods.
jfreerails.client.renderer.MyRenderersRoot.getTrackPieceView
Javadoc:
No Javadoc available
Method code:
@Override
public TrackPieceRenderer getTrackPieceView(int i) {
throw new UnsupportedOperationException("Not supported yet.");
}
No outgoing methods.
jfreerails.client.renderer.MyRenderersRoot.getWagonImages
Javadoc:
No Javadoc available
Method code:
@Override
public TrainImages getWagonImages(int type) {
return this.trainImages;
}
No outgoing methods.
jfreerails.client.renderer.MyRenderersRoot.validate
Javadoc:
No Javadoc available
Method code:
@Override
public boolean validate(ReadOnlyWorld world) {
throw new UnsupportedOperationException("Not supported yet.");
}
No outgoing methods.
jfreerails.client.renderer.NullTrackPieceRenderer.drawTrackPieceIcon
Javadoc:
No Javadoc available
Method code:
/*
* @see TrackPieceView#drawTrackPieceIcon(int, Graphics, int, int,
* Dimension)
*/
public void drawTrackPieceIcon(int trackTemplate, Graphics g, int x, int y,
Dimension tileSize) {
// Draw nothing since there no track here.
}
No outgoing methods.
jfreerails.client.renderer.NullTrackPieceRenderer.dumpImages
Javadoc:
No Javadoc available
Method code:
public void dumpImages(ImageManager imageManager) {
// TODO Auto-generated method stub
}
No outgoing methods.
jfreerails.client.renderer.NullTrackPieceRenderer.getTrackPieceIcon
Javadoc:
No Javadoc available
Method code:
/*
* @see TrackPieceView#getTrackPieceIcon(int)
*/
public Image getTrackPieceIcon(int trackTemplate) {
return null;
}
No outgoing methods.
jfreerails.client.renderer.RenderersRoot.getEngineImages
Javadoc:
No Javadoc available
Method code:
TrainImages getEngineImages(int type);
No outgoing methods.
jfreerails.client.renderer.RenderersRoot.getImage
Javadoc:
No Javadoc available
Method code:
Image getImage(String relativeFilename) throws IOException;
No outgoing methods.
jfreerails.client.renderer.RenderersRoot.getScaledImage
Javadoc:
No Javadoc available
Method code:
Image getScaledImage(String relativeFilename, int height) throws IOException;
No outgoing methods.
jfreerails.client.renderer.RenderersRoot.getTrackPieceView
Javadoc:
No Javadoc available
Method code:
TrackPieceRenderer getTrackPieceView(int i);
No outgoing methods.
jfreerails.client.renderer.RenderersRoot.getWagonImages
Javadoc:
No Javadoc available
Method code:
TrainImages getWagonImages(int type);
No outgoing methods.
jfreerails.client.renderer.RenderersRoot.validate
Javadoc:
No Javadoc available
Method code:
boolean validate(ReadOnlyWorld world);
No outgoing methods.
jfreerails.client.renderer.RiverStyleTileRenderer.dumpImages
Javadoc:
No Javadoc available
Method code:
@Override
public void dumpImages(ImageManager imageManager) {
for (int i = 0; i < this.getTileIcons().length; i++) {
imageManager.setImage(generateRelativeFileName(i), this
.getTileIcons()[i]);
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.RiverStyleTileRenderer.generateFileNameNumber
Javadoc:
No Javadoc available
Method code:
@Override
protected String generateFileNameNumber(int i) {
return BinaryNumberFormatter.formatWithLowBitOnLeft(i, 4);
}
Outgoing Methods (calls):
jfreerails.client.renderer.RiverStyleTileRenderer.selectTileIcon
Javadoc:
No Javadoc available
Method code:
@Override
public int selectTileIcon(int x, int y, ReadOnlyWorld w) {
int iconNumber = 0;
for (int i = 0; i < 4; i++) {
iconNumber = iconNumber << 1;
iconNumber = iconNumber
| checkTile(x + X_LOOK_AT[i], y + Y_LOOK_AT[i], w);
}
return iconNumber;
}
Outgoing Methods (calls):
jfreerails.client.renderer.SpecialTileRenderer.dumpImages
Javadoc:
/** * Sets the image for this tile renderer using the generated filename and the first tile icon. * This method delegates to {@link ImageManager#setImage(String, java.awt.Image)} to associate * the generated filename with the tile's primary icon. * * @param imageManager The image manager responsible for handling image resources. * * @see #generateFilename() * @see #getTileIcons() */
Method code:
@Override
public void dumpImages(ImageManager imageManager) {
imageManager.setImage(generateFilename(), this.getTileIcons()[0]);
}
Outgoing Methods (calls):
jfreerails.client.renderer.SpecialTileRenderer.generateFileNameNumber
Javadoc:
No Javadoc available
Method code:
@Override
protected String generateFileNameNumber(int i) {
throw new UnsupportedOperationException();
}
No outgoing methods.
jfreerails.client.renderer.SpecialTileRenderer.generateFilename
Javadoc:
No Javadoc available
Method code:
private String generateFilename() {
return "terrain" + File.separator + this.getTerrainType() + ".png";
}
Outgoing Methods (calls):
jfreerails.client.renderer.SpecialTileRenderer.renderTile
Javadoc:
No Javadoc available
Method code:
@Override
public void renderTile(java.awt.Graphics g, int renderX, int renderY,
int mapX, int mapY, ReadOnlyWorld w) {
if (parentTileView != null) {
parentTileView.renderTile(g, renderX, renderY, mapX, mapY, w);
} else {
logger.warning("parent tileView==null");
}
Image icon = this.getIcon(mapX, mapX, w);
if (null != icon) {
g.drawImage(icon, renderX, renderY, null);
} else {
logger.warning("special tileView icon==null");
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.SpecialTileRenderer.selectTileIcon
Javadoc:
No Javadoc available
Method code:
@Override
public int selectTileIcon(int x, int y, ReadOnlyWorld w) {
return 0;
}
No outgoing methods.
jfreerails.client.renderer.SquareTileBackgroundRenderer.paintBufferRectangle
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintBufferRectangle(int x, int y, int width, int height) {
// Fix for bug [ 1303162 ]
// If the buffer hasn't been set yet, don't try and refresh it!
if (null != super.backgroundBuffer) {
Graphics gg = bg.create();
gg.setClip(x, y, width, height);
gg.translate(-bufferRect.x, -bufferRect.y);
mapView.paintRect(gg, bufferRect);
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.SquareTileBackgroundRenderer.paintTile
Javadoc:
No Javadoc available
Method code:
public void paintTile(Graphics g, int tileX, int tileY) {
mapView.paintTile(g, tileX, tileY);
}
Outgoing Methods (calls):
jfreerails.client.renderer.SquareTileBackgroundRenderer.refreshTile
Javadoc:
No Javadoc available
Method code:
public void refreshTile(int x, int y) {
// The backgroundBuffer gets created on the first call to
// backgroundBuffer.paintRect(..)
// so we need a check here to avoid a null pointer exception.
if (null != super.backgroundBuffer) {
Graphics gg = bg.create();
gg.translate(-bufferRect.x, -bufferRect.y);
mapView.paintTile(gg, x, y);
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.SquareTileBackgroundRendererTest.testRefreshBeforeBufferIsSet
Javadoc:
/** Testcase to reproduce bug [ 1303162 ] Unexpected Exception:*/
Method code:
/** Testcase to reproduce bug [ 1303162 ] Unexpected Exception:*/
public void testRefreshBeforeBufferIsSet(){
SquareTileBackgroundRenderer stbr = new SquareTileBackgroundRenderer(renderer);
stbr.refreshAll();
stbr.refreshTile(1, 2);
}
Outgoing Methods (calls):
jfreerails.client.renderer.StandardTileRenderer.dumpImages
Javadoc:
/** * Dumps the tile's image by generating a filename and setting it via the provided ImageManager. * This method uses {@link #generateFilename()} to determine the filename and retrieves the first tile icon * from {@link #getTileIcons()} to associate with the image. * * @param imageManager The ImageManager responsible for handling image operations. */
Method code:
@Override
public void dumpImages(ImageManager imageManager) {
imageManager.setImage(generateFilename(), this.getTileIcons()[0]);
}
Outgoing Methods (calls):
jfreerails.client.renderer.StandardTileRenderer.generateFileNameNumber
Javadoc:
No Javadoc available
Method code:
@Override
protected String generateFileNameNumber(int i) {
throw new UnsupportedOperationException();
}
No outgoing methods.
jfreerails.client.renderer.StandardTileRenderer.generateFilename
Javadoc:
No Javadoc available
Method code:
public static String generateFilename(String typeName) {
return "terrain" + File.separator + typeName + ".png";
}
No outgoing methods.
jfreerails.client.renderer.StationBoxRenderer.calculateCarLoads
Javadoc:
/** * The length of the returned array is the number of complete carloads of * the specified cargo category in the specified bundle. The values in the * array are the type of the cargo. E.g. if the bundle contained 2 carloads * of cargo type 3 and 1 of type 7, {3, 3, 7} would be returned. */
Method code:
/**
* The length of the returned array is the number of complete carloads of
* the specified cargo category in the specified bundle. The values in the
* array are the type of the cargo. E.g. if the bundle contained 2 carloads
* of cargo type 3 and 1 of type 7, {3, 3, 7} would be returned.
*/
private int[][] calculateCarLoads(ImmutableCargoBundle cb) {
int categories = CargoType.getNumberOfCategories();
int numCargoTypes = w.size(SKEY.CARGO_TYPES);
int[] numberOfCarLoads = new int[categories];
int[][] cars = new int[categories][numCargoTypes];
for (int i = 0; i < numCargoTypes; i++) {
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, i);
int carsOfThisCargo = cb.getAmount(i)
/ WagonType.UNITS_OF_CARGO_PER_WAGON;
numberOfCarLoads[ct.getCategory().getNumber()] += carsOfThisCargo;
cars[ct.getCategory().getNumber()][i] += carsOfThisCargo;
}
int[][] returnMatrix = new int[categories][];
for (int category = 0; category < categories; category++) {
int[] returnValue = new int[numberOfCarLoads[category]];
int arrayIndex = 0;
for (int cargoType = 0; cargoType < numCargoTypes; cargoType++) {
for (int j = 0; j < cars[category][cargoType]; j++) {
returnValue[arrayIndex] = cargoType;
arrayIndex++;
}
}
returnMatrix[category] = returnValue;
}
return returnMatrix;
}
Outgoing Methods (calls):
jfreerails.client.renderer.StationBoxRenderer.paint
Javadoc:
No Javadoc available
Method code:
public void paint(Graphics2D g) {
Boolean showCargoWaiting = (Boolean) modelRoot
.getProperty(ModelRoot.Property.SHOW_CARGO_AT_STATIONS);
if (showCargoWaiting.booleanValue()) {
/* We only show the station boxes for the current player. */
FreerailsPrincipal principal = modelRoot.getPrincipal();
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
while (wi.next()) { // loop over non null stations
StationModel station = (StationModel) wi.getElement();
int positionX = (station.getStationX() * Constants.TILE_SIZE)
+ Constants.TILE_SIZE / 2;
int positionY = (station.getStationY() * Constants.TILE_SIZE)
+ Constants.TILE_SIZE * 2;
Rectangle r = new Rectangle(positionX, positionY, MAX_WIDTH,
MAX_HEIGHT);
g.setColor(bgColor);
g.fillRect(positionX, positionY, MAX_WIDTH, MAX_HEIGHT);
g.setColor(Color.WHITE);
g.setStroke(new BasicStroke(1f));
g.drawRect(positionX, positionY, MAX_WIDTH, MAX_HEIGHT);
ImmutableCargoBundle cb = (ImmutableCargoBundle) w.get(
principal, KEY.CARGO_BUNDLES, station
.getCargoBundleID());
int[][] carsLoads = calculateCarLoads(cb);
for (int category = 0; category < CargoType
.getNumberOfCategories(); category++) {
int alternateWidth = (MAX_WIDTH - 2 * SPACING)
/ (carsLoads[category].length + 1);
int xOffsetPerWagon = Math.min(wagonImageWidth,
alternateWidth);
for (int car = 0; car < carsLoads[category].length; car++) {
int x = positionX + (car * xOffsetPerWagon)
+ SPACING;
int y = positionY
+ (category * (WAGON_IMAGE_HEIGHT + SPACING));
int cargoType = carsLoads[category][car];
g.drawImage(cargoImages[cargoType], x, y, null);
}
}
}
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.StationNamesRenderer.paint
Javadoc:
No Javadoc available
Method code:
public void paint(Graphics2D g) {
int rectWidth;
int rectHeight;
int rectX;
int rectY;
float visibleAdvance;
float textX;
float textY;
StationModel tempStation;
String stationName;
int positionX;
int positionY;
Boolean showStationNames = (Boolean) modelRoot
.getProperty(ModelRoot.Property.SHOW_STATION_NAMES);
Boolean showStationBorders = (Boolean) modelRoot
.getProperty(ModelRoot.Property.SHOW_STATION_BORDERS);
FontRenderContext frc = g.getFontRenderContext();
TextLayout layout;
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
// draw station names onto map
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
while (wi.next()) { // loop over non null stations
tempStation = (StationModel) wi.getElement();
int x = tempStation.getStationX();
int y = tempStation.getStationY();
// First draw station sphere of influence
if (showStationBorders.booleanValue()) {
FreerailsTile tile = (FreerailsTile) w.getTile(x, y);
int radius = tile.getTrackPiece().getTrackRule().getStationRadius();
int diameterInPixels = (radius * 2 + 1) * 30;
int radiusX = (x - radius) * 30;
int radiusY = (y - radius) * 30;
g.setColor(Color.WHITE);
g.setStroke(dashed);
g.draw(new RoundRectangle2D.Double(radiusX, radiusY,
diameterInPixels, diameterInPixels, 10, 10));
}
// Then draw the station name.
if (showStationNames.booleanValue()) {
stationName = tempStation.getStationName();
positionX = (x * 30) + 15;
positionY = (y * 30) + 30;
layout = new TextLayout(stationName, font, frc);
visibleAdvance = layout.getVisibleAdvance();
rectWidth = (int) (visibleAdvance * 1.2);
rectHeight = (int) (fontSize * 1.5);
rectX = (positionX - (rectWidth / 2));
rectY = positionY;
g.setColor(bgColor);
g.fillRect(rectX, rectY, rectWidth, rectHeight);
textX = (positionX - (visibleAdvance / 2));
textY = positionY + fontSize + 1;
g.setColor(textColor);
layout.draw(g, textX, textY);
g.setStroke(new BasicStroke(1.0f));
// draw a border 1 pixel inside the edges of the rectangle
g.draw(new Rectangle(rectX + 1, rectY + 1, rectWidth - 3,
rectHeight - 3));
}
}
}
// end FOR loop
}
Outgoing Methods (calls):
jfreerails.client.renderer.StationRadiusRenderer.hide
Javadoc:
No Javadoc available
Method code:
public void hide() {
ModelRoot.Value lastCursorMode = (ModelRoot.Value) modelRoot
.getProperty(ModelRoot.Property.PREVIOUS_CURSOR_MODE);
assert !lastCursorMode
.equals(ModelRoot.Value.PLACE_STATION_CURSOR_MODE);
modelRoot.setProperty(ModelRoot.Property.CURSOR_MODE, lastCursorMode);
modelRoot.setProperty(Property.IGNORE_KEY_EVENTS, Boolean.FALSE);
}
Outgoing Methods (calls):
jfreerails.client.renderer.StationRadiusRenderer.paint
Javadoc:
No Javadoc available
Method code:
public void paint(Graphics2D g) {
if (modelRoot.getProperty(ModelRoot.Property.CURSOR_MODE).equals(
Value.PLACE_STATION_CURSOR_MODE)) {
g.setStroke(new BasicStroke(2f));
g.setColor(borderColor);
g.drawRect(tileSize * (x - radius), tileSize * (y - radius),
tileSize * (2 * radius + 1), tileSize * (2 * radius + 1));
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.StationRadiusRenderer.setBorderColor
Javadoc:
No Javadoc available
Method code:
public void setBorderColor(Color c) {
borderColor = c;
}
No outgoing methods.
jfreerails.client.renderer.StationRadiusRenderer.setPosition
Javadoc:
No Javadoc available
Method code:
public void setPosition(int x, int y) {
this.x = x;
this.y = y;
}
No outgoing methods.
jfreerails.client.renderer.StationRadiusRenderer.setRadius
Javadoc:
No Javadoc available
Method code:
public void setRadius(int radius) {
this.radius = radius;
}
No outgoing methods.
jfreerails.client.renderer.StationRadiusRenderer.show
Javadoc:
No Javadoc available
Method code:
public void show() {
if (!modelRoot
.is(Property.CURSOR_MODE, Value.PLACE_STATION_CURSOR_MODE)) {
modelRoot.setProperty(Property.PREVIOUS_CURSOR_MODE, modelRoot
.getProperty(Property.CURSOR_MODE));
modelRoot.setProperty(Property.CURSOR_MODE,
Value.PLACE_STATION_CURSOR_MODE);
modelRoot.setProperty(Property.IGNORE_KEY_EVENTS, Boolean.TRUE);
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.TerrainLayer.paintRect
Javadoc:
No Javadoc available
Method code:
public void paintRect(Graphics g, Rectangle visibleRect) {
throw new UnsupportedOperationException(
"Method not yet implemented.");
}
No outgoing methods.
jfreerails.client.renderer.TerrainLayer.paintRectangleOfTiles
Javadoc:
No Javadoc available
Method code:
private void paintRectangleOfTiles(Graphics g, int x, int y, int width,
int height) {
paintRectangleOfTiles(g, new Rectangle(x, y, width, height));
}
Outgoing Methods (calls):
jfreerails.client.renderer.TerrainLayer.paintTile
Javadoc:
No Javadoc available
Method code:
public void paintTile(Graphics g, Point tile) {
int screenX = tileSize.width * tile.x;
int screenY = tileSize.height * tile.y;
if ((tile.x >= 0) && (tile.x < mapSize.width) && (tile.y >= 0)
&& (tile.y < mapSize.height)) {
TerrainTile tt = (TerrainTile) w.getTile(tile.x, tile.y);
int typeNumber = tt.getTerrainTypeID();
TileRenderer tr = tiles.getTileViewWithNumber(typeNumber);
if (null == tr) {
logger.warning("No tile renderer for " + typeNumber);
} else {
tr.renderTile(g, screenX, screenY, tile.x, tile.y, w);
}
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.TerrainLayer.refreshAll
Javadoc:
No Javadoc available
Method code:
public void refreshAll() {
}
No outgoing methods.
jfreerails.client.renderer.TerrainLayer.refreshTile
Javadoc:
/** * Refreshes the tile located at the specified coordinates (x, y). * This method updates the tile's state or appearance to reflect any changes. * * @param x the x-coordinate of the tile to refresh * @param y the y-coordinate of the tile to refresh */
Method code:
public void refreshTile(int x, int y) {
}
No outgoing methods.
jfreerails.client.renderer.TileRenderer.dumpImages
Javadoc:
/** Adds the images this TileRenderer uses to the specified ImageManager. */
Method code:
/** Adds the images this TileRenderer uses to the specified ImageManager. */
void dumpImages(ImageManager imageManager);
No outgoing methods.
jfreerails.client.renderer.TileRenderer.getDefaultIcon
Javadoc:
No Javadoc available
Method code:
Image getDefaultIcon();
No outgoing methods.
jfreerails.client.renderer.TileRenderer.renderTile
Javadoc:
No Javadoc available
Method code:
void renderTile(java.awt.Graphics g, int renderX, int renderY, int mapX,
int mapY, ReadOnlyWorld w);
No outgoing methods.
jfreerails.client.renderer.TileRendererList.getTileViewWithNumber
Javadoc:
No Javadoc available
Method code:
TileRenderer getTileViewWithNumber(int i);
No outgoing methods.
jfreerails.client.renderer.TileRendererList.validate
Javadoc:
/** * Checks whether this tile view list has tile views for all the terrain * types in the specified list. */
Method code:
/**
* Checks whether this tile view list has tile views for all the terrain
* types in the specified list.
*/
boolean validate(ReadOnlyWorld world);
No outgoing methods.
jfreerails.client.renderer.TileRendererListImpl.getTileViewWithNumber
Javadoc:
No Javadoc available
Method code:
public TileRenderer getTileViewWithNumber(int i) {
return tiles[i];
}
No outgoing methods.
jfreerails.client.renderer.TileRendererListImpl.validate
Javadoc:
No Javadoc available
Method code:
public boolean validate(ReadOnlyWorld w) {
// There should a TileRenderer for each terrain type.
return w.size(SKEY.TERRAIN_TYPES) == tiles.length;
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrackLayer.paintRect
Javadoc:
No Javadoc available
Method code:
public void paintRect(Graphics g, Rectangle visibleRect) {
throw new UnsupportedOperationException(
"Method not yet implemented.");
}
No outgoing methods.
jfreerails.client.renderer.TrackLayer.paintRectangleOfTiles
Javadoc:
/** * Paints a rectangle of tiles onto the supplied graphics context. * * @param g * The graphics context on which the tiles get painted. * @param tilesToPaint * The rectangle, measured in tiles, to paint. */
Method code:
/**
* Paints a rectangle of tiles onto the supplied graphics context.
*
* @param g
* The graphics context on which the tiles get painted.
* @param tilesToPaint
* The rectangle, measured in tiles, to paint.
*/
public void paintRectangleOfTiles(Graphics g, Rectangle tilesToPaint) {
/*
* Track can overlap the adjacent terrain tiles by half a tile. This
* means that we need to paint the track from the tiles bordering
* the specified rectangle of tiles (tilesToPaint). To prevent
* unnecessary painting, we set the clip to expose only the rectangle
* of tilesToPaint.
*/
Graphics tempG = g;
Point tile = new Point();
for (tile.x = tilesToPaint.x - 1; tile.x < (tilesToPaint.x
+ tilesToPaint.width + 1); tile.x++) {
for (tile.y = tilesToPaint.y - 1; tile.y < (tilesToPaint.y
+ tilesToPaint.height + 1); tile.y++) {
if ((tile.x >= 0) && (tile.x < mapSize.width)
&& (tile.y >= 0) && (tile.y < mapSize.height)) {
FreerailsTile ft = (FreerailsTile)w.getTile(tile.x, tile.y);
TrackPiece tp = ft.getTrackPiece();
int graphicsNumber = tp.getTrackGraphicID();
int ruleNumber = tp.getTrackTypeID();
if (ruleNumber != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
TrackPieceRenderer trackPieceView = rr.getTrackPieceView(ruleNumber);
trackPieceView.drawTrackPieceIcon(graphicsNumber,
tempG, tile.x, tile.y, tileSize);
}
}
}
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrackLayer.paintTile
Javadoc:
No Javadoc available
Method code:
public void paintTile(Graphics g, int tileX, int tileY) {
/*
* Since track tiles overlap the adjacent terrain tiles, we create a
* temporary Graphics object that only lets us draw on the selected
* tile.
*/
paintRectangleOfTiles(g, new Rectangle(tileX, tileY, 1, 1));
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrackLayer.refreshAll
Javadoc:
No Javadoc available
Method code:
public void refreshAll() {
}
No outgoing methods.
jfreerails.client.renderer.TrackLayer.refreshTile
Javadoc:
No Javadoc available
Method code:
public void refreshTile(int x, int y) {
}
No outgoing methods.
jfreerails.client.renderer.TrackPieceRenderer.drawTrackPieceIcon
Javadoc:
No Javadoc available
Method code:
void drawTrackPieceIcon(int trackTemplate, java.awt.Graphics g, int x,
int y, java.awt.Dimension tileSize);
No outgoing methods.
jfreerails.client.renderer.TrackPieceRenderer.dumpImages
Javadoc:
/** Adds the images this TileRenderer uses to the specified ImageManager. */
Method code:
/** Adds the images this TileRenderer uses to the specified ImageManager. */
void dumpImages(ImageManager imageManager);
No outgoing methods.
jfreerails.client.renderer.TrackPieceRenderer.getTrackPieceIcon
Javadoc:
No Javadoc available
Method code:
Image getTrackPieceIcon(int trackTemplate);
No outgoing methods.
jfreerails.client.renderer.TrackPieceRendererImpl.drawTrackPieceIcon
Javadoc:
No Javadoc available
Method code:
public void drawTrackPieceIcon(int trackTemplate, java.awt.Graphics g,
int x, int y, java.awt.Dimension tileSize) {
if ((trackTemplate > 511) || (trackTemplate < 0)) {
throw new java.lang.IllegalArgumentException("trackTemplate = "
+ trackTemplate + ", it should be in the range 0-511");
}
if (trackPieceIcons[trackTemplate] != null) {
int drawX = x * tileSize.width - tileSize.width / 2;
int drawY = y * tileSize.height - tileSize.height / 2;
g.drawImage(trackPieceIcons[trackTemplate], drawX, drawY, null);
}
}
No outgoing methods.
jfreerails.client.renderer.TrackPieceRendererImpl.dumpImages
Javadoc:
No Javadoc available
Method code:
public void dumpImages(ImageManager imageManager) {
for (int i = 0; i < 512; i++) {
if (trackPieceIcons[i] != null) {
String fileName = generateFilename(i, getTrackTypeName());
imageManager.setImage(fileName, trackPieceIcons[i]);
}
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrackPieceRendererImpl.generateFilename
Javadoc:
No Javadoc available
Method code:
public static String generateFilename(int i, String trackTypeName) {
String relativeFileNameBase = "track" + File.separator + trackTypeName;
int newTemplate = TrackConfiguration.from9bitTemplate(i)
.get8bitTemplate();
String fileName = relativeFileNameBase + "_"
+ BinaryNumberFormatter.formatWithLowBitOnLeft(newTemplate, 8)
+ ".png";
return fileName;
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrackPieceRendererImpl.getTrackPieceIcon
Javadoc:
No Javadoc available
Method code:
public Image getTrackPieceIcon(int trackTemplate) {
if ((trackTemplate > 511) || (trackTemplate < 0)) {
throw new java.lang.IllegalArgumentException("trackTemplate = "
+ trackTemplate + ", it should be in the range 0-511");
}
return trackPieceIcons[trackTemplate];
}
No outgoing methods.
jfreerails.client.renderer.TrackPieceRendererImpl.getTrackTypeName
Javadoc:
No Javadoc available
Method code:
private String getTrackTypeName() {
return typeName;
}
No outgoing methods.
jfreerails.client.renderer.TrackPieceRendererList.getTrackPieceView
Javadoc:
No Javadoc available
Method code:
public TrackPieceRenderer getTrackPieceView(int i) {
if (NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER == i) {
return NullTrackPieceRenderer.instance;
}
return trackPieceViewArray[i];
}
No outgoing methods.
jfreerails.client.renderer.TrackPieceRendererList.validate
Javadoc:
No Javadoc available
Method code:
public boolean validate(ReadOnlyWorld w) {
boolean okSoFar = true;
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
Iterator<TrackConfiguration> legalConfigurationsIterator = trackRule
.getLegalConfigurationsIterator();
TrackPieceRenderer trackPieceView = this.getTrackPieceView(i);
if (null == trackPieceView) {
logger
.warning("No track piece view for the following track type: "
+ trackRule.getTypeName());
return false;
}
while (legalConfigurationsIterator.hasNext()) {
TrackConfiguration trackConfig = legalConfigurationsIterator
.next();
int trackGraphicsNo = trackConfig.getTrackGraphicsID();
Image img = trackPieceView.getTrackPieceIcon(trackGraphicsNo);
if (null == img) {
logger
.warning("No track piece image for the following track type: "
+ trackRule.getTypeName()
+ ", with configuration: "
+ trackGraphicsNo);
okSoFar = false;
}
}
}
return okSoFar;
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrainImages.generateOverheadFilename
Javadoc:
No Javadoc available
Method code:
public static String generateOverheadFilename(String name, int i) {
Step[] vectors = Step.getList();
return "trains" + File.separator + "overhead" + File.separator + name
+ "_" + vectors[i].toAbrvString() + ".png";
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrainImages.generateSideOnFilename
Javadoc:
/** * Generates the filename for a side-on view train image based on the provided train name. * * @param name the name of the train used to construct the filename * @return the full path to the side-on image file, including the directory structure and .png extension */
Method code:
public static String generateSideOnFilename(String name) {
return "trains" + File.separator + "sideon" + File.separator + name
+ ".png";
}
No outgoing methods.
jfreerails.client.renderer.TrainImages.getOverheadHighlightImage
Javadoc:
/** * @param direction * @return the image to render under the wagon/engine image * when the train is selects/focused. */
Method code:
/**
* @param direction
* @return the image to render under the wagon/engine image
* when the train is selects/focused.
*/
public Image getOverheadHighlightImage(int direction, Highlight h) {
if(h == Highlight.FOCUSED)
return overheadFocusedImages[direction];
if(h == Highlight.SELECTED)
return overheadSelectedImages[direction];
return null;
}
No outgoing methods.
jfreerails.client.renderer.TrainImages.getOverheadImage
Javadoc:
No Javadoc available
Method code:
public Image getOverheadImage(int direction) {
return overheadImages[direction];
}
No outgoing methods.
jfreerails.client.renderer.TrainImages.getSideOnImage
Javadoc:
No Javadoc available
Method code:
public Image getSideOnImage() {
return sideOnImage;
}
No outgoing methods.
jfreerails.client.renderer.TrainRenderer.calcPositions
Javadoc:
/** * Calculates the positions of the engine and each wagon on the map. * Intended to be used for rendering trains, for rendering highlights * around trains, and for determining if a mouse click was on a train. * * @param train * @param s * @return List of positions, one entry for the engine and one for each * wagon. */
Method code:
/**
* Calculates the positions of the engine and each wagon on the map.
* Intended to be used for rendering trains, for rendering highlights
* around trains, and for determining if a mouse click was on a train.
*
* @param train
* @param s
* @return List of positions, one entry for the engine and one for each
* wagon.
*/
public List<Entry<Point, Step>> calcPositions(TrainModel train, TrainPositionOnMap s) {
List<Entry<Point, Step>> positions = new ArrayList<>(train.getLength() + 1);
FreerailsPathIterator it = s.path();
PathWalker pw = new PathWalkerImpl(it);
// Engine + wagons
for (int i = 0; i < train.getNumberOfWagons() + 1; i++) {
IntLine wagon = new IntLine();
IntLine line = new IntLine();
pw.stepForward(16);
boolean firstIteration = true;
while (pw.hasNext()) {
pw.nextSegment(line);
if (firstIteration) {
wagon.x1 = line.x1;
wagon.y1 = line.y1;
firstIteration = false;
}
}
wagon.x2 = line.x2;
wagon.y2 = line.y2;
Step v = Step
.getNearestVector(wagon.x2 - wagon.x1, wagon.y2 - wagon.y1);
Point wagonCenter = new Point((wagon.x2 + wagon.x1) / 2,
(wagon.y2 + wagon.y1) / 2);
positions.add(new AbstractMap.SimpleImmutableEntry<>(wagonCenter, v));
// The gap between wagons
pw.stepForward(8);
while (pw.hasNext()) {
pw.nextSegment(line);
}
}
return positions;
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrainRenderer.isHit
Javadoc:
No Javadoc available
Method code:
public boolean isHit(Point mousePosition, TrainModel train, List<Entry<Point, Step>> positions) {
for (int i = 0; i < positions.size(); i++) {
Entry<Point, Step> entry = positions.get(i);
Point p = entry.getKey();
int xDist = mousePosition.x - p.x;
int yDist = mousePosition.y - p.y;
int sumSquares = xDist * xDist + yDist * yDist;
if( sumSquares > 15 * 15){
continue;
}
TrainImages trainImages;
if (i == 0) {
trainImages = rr.getEngineImages(train.getEngineType());
} else {
int type = train.getWagon(i - 1);
trainImages = rr.getWagonImages(type);
}
BufferedImage image = (BufferedImage) trainImages.getOverheadImage(entry.getValue().getID());
int x = xDist + 15;
int y = yDist + 15;
Color c = new Color(image.getRGB(x, y), true);
int alpha = c.getAlpha();
if(alpha > 128){
return true;
}
}
return false;
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrainRenderer.paintTrain
Javadoc:
No Javadoc available
Method code:
public void paintTrain(Graphics g, TrainModel train, TrainPositionOnMap s, TrainImages.Highlight highlight) {
// If the train has been removed, it will be null!
if (train == null) {
return;
}
/*
* XXX HACK !! really our position ought to be defined at all times, but
* this is a workaround until we can fix movement
*/
if (s == null) {
return;
}
List<Entry<Point, Step>> positions = calcPositions(train, s);
if(null != highlight){
paintTrainHighlight(g, train, positions, highlight);
}
paintTrain(g, train, positions);
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrainRenderer.paintTrainCrash
Javadoc:
No Javadoc available
Method code:
// @SonnyZ
// This code renders the explosion that occurs when 2 trains crash on the
// map
public void paintTrainCrash(Graphics g, TrainPositionOnMap s) {
// check to see if there is a train
// if (s == null) {
// return;
// }
// // Get the image for that frame of the explosion
// Image explosionImage = rr
// .getExplosionImage(s.getFrameCt() - 1);
// // draw the image
// for (int i = 0; i < s.getLength() - 1; i++) {
// Point wagonCenter = new Point(s.getX(i), s.getY(i));
// g.drawImage(explosionImage, wagonCenter.x - 15, wagonCenter.y - 15, null);
//
// }
// // increment the frame count
// s.incrementFramCt();
}
No outgoing methods.
jfreerails.client.renderer.TrainRenderer.paintTrainHighlight
Javadoc:
No Javadoc available
Method code:
public void paintTrainHighlight(Graphics g, TrainModel train, List<Entry<Point, Step>> positions, TrainImages.Highlight highlight) {
for (int i = 0; i < positions.size(); i++) {
TrainImages trainImages;
if (i == 0) {
trainImages = rr.getEngineImages(train.getEngineType());
} else {
int type = train.getWagon(i - 1);
trainImages = rr.getWagonImages(type);
}
Entry<Point, Step> entry = positions.get(i);
Image image = trainImages.getOverheadHighlightImage(entry.getValue().getID(), highlight);
Point p = entry.getKey();
g.drawImage(image, p.x - 15, p.y - 15, null);
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrainRendererTest.isHit
Javadoc:
No Javadoc available
Method code:
public boolean isHit(Point wagonCenter, Point mouseClick, Step step) {
List<Map.Entry<Point, Step>> positions = new ArrayList<>();
positions.add(new AbstractMap.SimpleImmutableEntry<>(wagonCenter, step));
RenderersRoot rr = new MyRenderersRoot();
TrainModel train = new TrainModel(0);
TrainRenderer tr = new TrainRenderer(rr);
boolean hit = tr.isHit(mouseClick, train, positions);
return hit;
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrainRendererTest.testHit1
Javadoc:
No Javadoc available
Method code:
@Test
public void testHit1() {
Point wagonCenter = new Point(100, 100);
Point mouseClick = new Point(100, 100);
boolean hit = isHit(wagonCenter, mouseClick, Step.NORTH);
assertTrue(hit);
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrainRendererTest.testHit2
Javadoc:
No Javadoc available
Method code:
@Test
public void testHit2() {
Point wagonCenter = new Point(100, 100);
Point mouseClick = new Point(90, 100);
boolean hit = isHit(wagonCenter, mouseClick, Step.NORTH);
assertFalse(hit);
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrainRendererTest.testHit3
Javadoc:
No Javadoc available
Method code:
@Test
public void testHit3() {
Point wagonCenter = new Point(100, 100);
Point mouseClick = new Point(85, 100);
boolean hit = isHit(wagonCenter, mouseClick, Step.NORTH);
assertFalse(hit);
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrainRendererTest.testHit4
Javadoc:
No Javadoc available
Method code:
@Test
public void testHit4() {
Point wagonCenter = new Point(100, 100);
Point mouseClick = new Point(84, 100);
boolean hit = isHit(wagonCenter, mouseClick, Step.NORTH);
assertFalse(hit);
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrainRendererTest.testHit5
Javadoc:
No Javadoc available
Method code:
@Test
public void testHit5() {
Point wagonCenter = new Point(100, 100);
Point mouseClick = new Point(96, 100);
boolean hit = isHit(wagonCenter, mouseClick, Step.NORTH);
assertTrue(hit);
}
Outgoing Methods (calls):
jfreerails.client.renderer.TrainRendererTest.testTrainImages
Javadoc:
No Javadoc available
Method code:
@Test
public void testTrainImages() {
RenderersRoot rr = new MyRenderersRoot();
TrainImages wagonImages = rr.getWagonImages(0);
assertNotNull(wagonImages);
TrainImages engineImages = rr.getEngineImages(0);
assertNotNull(engineImages);
for (Step step : Step.getList()) {
Image overheadImage = wagonImages.getOverheadImage(step.getID());
assertTrue(overheadImage instanceof BufferedImage);
}
}
Outgoing Methods (calls):
jfreerails.client.renderer.Unknown.paintRect
Javadoc:
No Javadoc available
Method code:
public void paintRect(Graphics g, Rectangle visibleRect) {
}
No outgoing methods.
jfreerails.client.renderer.Unknown.paintTile
Javadoc:
No Javadoc available
Method code:
public void paintTile(Graphics g, int tileX, int tileY) {
}
No outgoing methods.
jfreerails.client.renderer.Unknown.refreshAll
Javadoc:
No Javadoc available
Method code:
public void refreshAll() {
}
No outgoing methods.
jfreerails.client.renderer.Unknown.refreshTile
Javadoc:
No Javadoc available
Method code:
public void refreshTile(int x, int y) {
}
No outgoing methods.
jfreerails.client.renderer.ZoomedOutMapRenderer.getInstance
Javadoc:
No Javadoc available
Method code:
public static ZoomedOutMapRenderer getInstance(ReadOnlyWorld world,
Dimension maxSize) {
// Work with doubles to avoid rounding errors.
double worldWidth = world.getMapWidth();
double worldHeight = world.getMapHeight();
double scale;
if (worldWidth / worldHeight > maxSize.getWidth() / maxSize.getHeight()) {
scale = maxSize.getWidth() / worldWidth;
} else {
scale = maxSize.getHeight() / worldHeight;
}
double height = scale * worldHeight;
double width = scale * worldWidth;
return new ZoomedOutMapRenderer(world, (int) width, (int) height, 0, 0,
world.getMapWidth(), world.getMapHeight());
}
Outgoing Methods (calls):
jfreerails.client.renderer.ZoomedOutMapRenderer.getMapSizeInPixels
Javadoc:
No Javadoc available
Method code:
/*
* @see NewMapView#getMapSizeInPixels()
*/
public Dimension getMapSizeInPixels() {
return new Dimension(imageWidth, imageHeight);
}
No outgoing methods.
jfreerails.client.renderer.ZoomedOutMapRenderer.getScale
Javadoc:
/** * Returns the scale factor as a float, calculated by dividing the image height * by the map height. This scale factor represents the zoom level applied to * the map rendering. * * @return the scale factor as a float value */
Method code:
public float getScale() {
return (float) imageHeight / (float) mapHeight;
}
No outgoing methods.
jfreerails.client.renderer.ZoomedOutMapRenderer.paintRect
Javadoc:
No Javadoc available
Method code:
public void paintRect(Graphics g, Rectangle visibleRect) {
renderOffScreenImage();
g.drawImage(mapImage, 0, 0, null);
}
Outgoing Methods (calls):
jfreerails.client.renderer.ZoomedOutMapRenderer.paintTile
Javadoc:
No Javadoc available
Method code:
public void paintTile(Graphics g, int tileX, int tileY) {
g.drawImage(mapImage, 0, 0, null);
}
No outgoing methods.
jfreerails.client.renderer.ZoomedOutMapRenderer.refresh
Javadoc:
/** * Redraw the whole map onto a new buffer. */
Method code:
/**
* Redraw the whole map onto a new buffer.
*/
private void refresh() {
isDirty = true;
/* free up memory used by the old image */
if (mapImage != null) {
mapImage.flush();
}
if (one2oneImage != null) {
one2oneImage.flush();
}
// if (mapGraphics != null) {
// mapGraphics.dispose();
// }
/* generate a 1:1 map of the terrain layer */
one2oneImage = defaultConfiguration.createCompatibleImage(mapWidth,
mapHeight, Transparency.TRANSLUCENT);
mapImage = defaultConfiguration.createCompatibleImage(imageWidth,
imageHeight, Transparency.OPAQUE);
Point tile = new Point();
for (tile.x = mapX; tile.x < mapWidth + mapX; tile.x++) {
for (tile.y = mapY; tile.y < mapHeight + mapY; tile.y++) {
FreerailsTile tt = (FreerailsTile) w.getTile(tile.x, tile.y);
if (tt.getTrackPiece().equals(NullTrackPiece.getInstance())) {
int typeNumber = tt.getTerrainTypeID();
TerrainType terrainType = (TerrainType) w.get(
SKEY.TERRAIN_TYPES, typeNumber);
one2oneImage.setRGB(tile.x - mapX, tile.y - mapY,
terrainType.getRGB());
} else {
/* black with alpha of 1 */
one2oneImage.setRGB(tile.x - mapX, tile.y - mapY,
0xff000000);
}
}
}
renderOffScreenImage();
}
Outgoing Methods (calls):
jfreerails.client.renderer.ZoomedOutMapRenderer.refreshAll
Javadoc:
No Javadoc available
Method code:
public void refreshAll() {
refresh();
}
Outgoing Methods (calls):
jfreerails.client.renderer.ZoomedOutMapRenderer.refreshTile
Javadoc:
No Javadoc available
Method code:
public void refreshTile(int x, int y) {
refreshTile(new Point(x, y));
}
Outgoing Methods (calls):
jfreerails.client.renderer.ZoomedOutMapRenderer.renderOffScreenImage
Javadoc:
No Javadoc available
Method code:
private void renderOffScreenImage() {
if (isDirty) {
Graphics2D mapGraphics = mapImage.createGraphics();
mapGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
mapGraphics.setClip(0, 0, imageWidth, imageHeight);
mapGraphics.clearRect(0, 0, imageWidth, imageHeight);
mapGraphics.drawImage(one2oneImage, affineTransform, null);
isDirty = false;
}
}
No outgoing methods.
jfreerails.client.top.BuildIndustryJPopupMenu.setCursorLocation
Javadoc:
No Javadoc available
Method code:
public void setCursorLocation(Point p) {
cursorLocation.x = p.x;
cursorLocation.y = p.y;
}
No outgoing methods.
jfreerails.client.top.BuildIndustryJPopupMenu.setup
Javadoc:
No Javadoc available
Method code:
public void setup(final ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
this.removeAll();
final NonNullElements it = new NonNullElements(SKEY.TERRAIN_TYPES,
modelRoot.getWorld());
while (it.next()) {
TerrainType type = (TerrainType) it.getElement();
final Money price = type.getBuildCost();
if (null != price) {
JMenuItem item = new JMenuItem(type.getDisplayName() + " "
+ price);
item.addActionListener(new ActionListener() {
private final int terrainType = it.getIndex();
public void actionPerformed(ActionEvent arg0) {
Move m1 = new ChangeTileMove(modelRoot.getWorld(),
cursorLocation, terrainType);
Transaction t = new AddItemTransaction(
Transaction.Category.INDUSTRIES, terrainType,
1, price.changeSign());
Move m2 = new AddTransactionMove(modelRoot
.getPrincipal(), t);
CompositeMove m3 = new CompositeMove(m1, m2);
MoveStatus ms = modelRoot.doMove(m3);
if (!ms.ok) {
modelRoot.setProperty(
ModelRoot.Property.CURSOR_MESSAGE,
ms.message);
}
}
});
add(item);
}
}
}
Outgoing Methods (calls):
jfreerails.client.top.BuildMenu.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ActionRoot actionRoot) {
this.removeAll();
this.setText("Build");
add(actionRoot.getBuildTrainDialogAction());
}
Outgoing Methods (calls):
jfreerails.client.top.ClientJFrame.exitForm
Javadoc:
/** Exit the Application. */
Method code:
/** Exit the Application. */
private void exitForm(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_exitForm
System.exit(0);
}// GEN-LAST:event_exitForm
No outgoing methods.
jfreerails.client.top.ClientJFrame.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
rhsjPanel = new javax.swing.JPanel();
mapOverview = gUIComponentFactory.createOverviewMap();
trainsJTabPane1 = gUIComponentFactory.createTrainsJTabPane();
lhsjPanel = new javax.swing.JPanel();
mainMapView = gUIComponentFactory.createMainMap();
statusjPanel = new javax.swing.JPanel();
datejLabel = gUIComponentFactory.createDateJLabel();
cashjLabel = gUIComponentFactory.createCashJLabel();
jMenuBar1 = new javax.swing.JMenuBar();
gameMenu = gUIComponentFactory.createGameMenu();
buildMenu = gUIComponentFactory.createBuildMenu();
BrokerMenu1 = gUIComponentFactory.createBrokerMenu();
displayMenu = gUIComponentFactory.createDisplayMenu();
reportsMenu = gUIComponentFactory.createReportsMenu();
helpMenu = gUIComponentFactory.createHelpMenu();
getContentPane().setLayout(new java.awt.GridBagLayout());
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
rhsjPanel.setLayout(new java.awt.GridBagLayout());
rhsjPanel.add(mapOverview, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
rhsjPanel.add(trainsJTabPane1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
getContentPane().add(rhsjPanel, gridBagConstraints);
lhsjPanel.setLayout(new java.awt.GridBagLayout());
mainMapView.setAlignmentX(0.0F);
mainMapView.setAlignmentY(0.0F);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
lhsjPanel.add(mainMapView, gridBagConstraints);
statusjPanel.add(datejLabel);
statusjPanel.add(cashjLabel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
lhsjPanel.add(statusjPanel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(lhsjPanel, gridBagConstraints);
gameMenu.setText("Game");
jMenuBar1.add(gameMenu);
buildMenu.setText("Build");
jMenuBar1.add(buildMenu);
BrokerMenu1.setText("Broker");
jMenuBar1.add(BrokerMenu1);
displayMenu.setText("Display");
jMenuBar1.add(displayMenu);
reportsMenu.setText("Reports");
jMenuBar1.add(reportsMenu);
helpMenu.setText("Help");
jMenuBar1.add(helpMenu);
setJMenuBar(jMenuBar1);
pack();
}// GEN-END:initComponents
Outgoing Methods (calls):
jfreerails.client.top.ClientJFrame.main
Javadoc:
No Javadoc available
Method code:
public static void main(String args[]) {
new ClientJFrame(new GUIComponentFactoryTestImpl()).setVisible(true);
}
No outgoing methods.
jfreerails.client.top.ClientJFrame.setup
Javadoc:
No Javadoc available
Method code:
private void setup(GUIComponentFactory gcf) {
this.gUIComponentFactory = gcf;
initComponents();
gUIComponentFactory.createDateJLabel();
}
Outgoing Methods (calls):
jfreerails.client.top.CursorMouseAdapter.mouseClicked
Javadoc:
No Javadoc available
Method code:
@Override
public void mouseClicked(MouseEvent evt) {
boolean isDoubleClick = evt.getClickCount() == 2;
ReadOnlyWorld w = modelRoot.getWorld();
FreerailsPrincipal principal = modelRoot.getPrincipal();
if (SwingUtilities.isLeftMouseButton(evt)) {
int x = evt.getX();
int y = evt.getY();
Double time = (Double) modelRoot.getProperty(Property.TIME);
int clickedTrain = -1;
//Iterate in reverse order since later trains are rendered over earlier ones.
for (int i = w.size(principal, KEY.TRAINS) -1; i >= 0 ; i--) {
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS, i);
TrainAccessor ta = new TrainAccessor(w, principal, i);
TrainPositionOnMap pos = ta.findPosition(time);
List<Map.Entry<Point, Step>> positions = trainRenderer.calcPositions(train, pos);
boolean hit = trainRenderer.isHit(evt.getPoint(), train, positions);
if(hit){
clickedTrain = i;
break;
}
}
if (clickedTrain != -1) {
modelRoot.setProperty(Property.SELECTED_TRAIN, clickedTrain);
if (isDoubleClick) {
dialogueBoxController.showTrainOrders(clickedTrain);
}
} else {
if (isDoubleClick) {
ImPoint cursorPosition = (ImPoint) modelRoot.getProperty(Property.CURSOR_POSITION);
dialogueBoxController.showStationOrTerrainInfo(cursorPosition.x,
cursorPosition.y);
}
}
}
}
Outgoing Methods (calls):
jfreerails.client.top.CursorMouseAdapter.mouseDragged
Javadoc:
No Javadoc available
Method code:
@Override
public void mouseDragged(MouseEvent evt
) {
BuildMode trackBuilderMode = trackBuilder.getTrackBuilderMode();
/*
* Fix for bug [ 972866 ] Build track by dragging - only when build
* track selected
* Fix for bug [1537413 ] Exception when building station.
*/
boolean trackBuildingOn = (trackBuilderMode == BUILD_TRACK)
|| (trackBuilderMode == REMOVE_TRACK)
|| (trackBuilderMode == UPGRADE_TRACK);
trackBuildingOn = trackBuildingOn
&& (modelRoot.getProperty(ModelRoot.Property.CURSOR_MODE) == ModelRoot.Value.BUILD_TRACK_CURSOR_MODE);
if (SwingUtilities.isLeftMouseButton(evt) && pressedInside
&& trackBuildingOn && !ignoreDragging) {
setIgnoreKeyEvents(true);
int x = evt.getX();
int y = evt.getY();
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
int tileX = x / tileSize.width;
int tileY = y / tileSize.height;
/*
* See the javadoc for JComponent.setAutoscrolls(boolean
* autoscrolls)
*/
assert mapView.getAutoscrolls();
// Scroll view if necessary.
if (!mapView.getVisibleRect().contains(x, y)) {
/*
* Making the rectangle we scroll to 2 tiles wide and
* centered on x, y means that we scroll at least one tile.
* This stops painfully slow scrolling in full screen mode
* when the mouse cannot be dragged far from the viewport
* since it hits the screen edge.
*/
Rectangle r = new Rectangle(x - tileSize.width, y
- tileSize.height, 2 * tileSize.width,
2 * tileSize.height);
mapView.scrollRectToVisible(r);
}
ImPoint to = new ImPoint(
tileX, tileY);
buildTrack.setProposedTrack(to, trackBuilder);
mapView.requestFocus();
}
}
Outgoing Methods (calls):
jfreerails.client.top.CursorMouseAdapter.mousePressed
Javadoc:
No Javadoc available
Method code:
@Override
public void mousePressed(MouseEvent evt
) {
if (SwingUtilities.isLeftMouseButton(evt)) {
ignoreDragging = false;
int x = evt.getX();
int y = evt.getY();
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
// only jump - no track building
moveCursorJump(new ImPoint(x / tileSize.width, y
/ tileSize.height));
mapView.requestFocus();
pressedInside = true;
/*
* Fix for bug [ 972866 ] Build track by dragging - only when
* build track selected
*/
boolean isBuildTrackModeSet = trackBuilder
.getTrackBuilderMode() == BUILD_TRACK;
if (isBuildTrackModeSet) {
buildTrack.show();
}
} else if (SwingUtilities.isRightMouseButton(evt)) {
// Cancel building track.
buildTrack.hide();
ignoreDragging = true;
setIgnoreKeyEvents(false);
}
}
Outgoing Methods (calls):
jfreerails.client.top.CursorMouseAdapter.mouseReleased
Javadoc:
No Javadoc available
Method code:
@Override
public void mouseReleased(MouseEvent evt
) {
if (SwingUtilities.isLeftMouseButton(evt)) {
ignoreDragging = false;
setIgnoreKeyEvents(false);
// build a railroad from x,y to current cursor position
if (pressedInside && buildTrack.isBuilding()
&& buildTrack.isBuildTrackSuccessful()) {
// Fix for bug [ 997088 ]
// Is current posisition different from original position?
int x = evt.getX();
int y = evt.getY();
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
int tileX = x / tileSize.width;
int tileY = y / tileSize.height;
if (getCursorPosition().x != tileX
|| getCursorPosition().y != tileY) {
// copy WorldDifferences from buildTrack to World
ImPoint newPosition = buildTrack
.updateWorld(trackBuilder);
setCursorPosition(newPosition);
}
}
pressedInside = false;
buildTrack.hide();
}
}
Outgoing Methods (calls):
jfreerails.client.top.FPScounter.drawFPS
Javadoc:
No Javadoc available
Method code:
void drawFPS(Graphics2D g) {
int rectWidth;
int rectHeight;
int rectX;
int rectY;
int positionX = 50;
int positionY = 70;
Color textColor = Color.WHITE;
String[] lines = newFPSstr.split("\n");
rectWidth = 60;
rectHeight = (int) ((fontSize + 1) * 1.2 * lines.length);
rectY = (int) (positionY - fontSize * 1.2);
rectX = positionX;
g.setColor(bgColor);
g.fillRect(rectX, rectY, rectWidth, rectHeight);
g.setColor(textColor);
// g.setFont(font);
for (String s : lines) {
g.drawString(s, positionX, positionY);
positionY += fontSize * 1.2;
}
}
No outgoing methods.
jfreerails.client.top.FPScounter.updateFPSCounter
Javadoc:
No Javadoc available
Method code:
// Display the average number of FPS.
void updateFPSCounter() {
long currentTime = System.nanoTime();
if (newFrameCount == 0) {
lastFrameTime = currentTime;
}
double dt = currentTime - lastFrameTime;
double fps = 1000000000d / dt;
fpsValues[newFrameCount % fpsValues.length] = fps;
newFrameCount++;
int n = fpsValues.length;
if (newFrameCount > fpsValues.length) {
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
double mean = 0;
for (int i = 0; i < fpsValues.length; i++) {
min = Math.min(min, fpsValues[i]);
max = Math.max(max, fpsValues[i]);
mean += fpsValues[i];
}
mean = mean / n;
if (mean > max)
throw new IllegalStateException();
if (mean < min)
throw new IllegalStateException();
double variance = 0;
for (int i = 0; i < fpsValues.length; i++) {
double xMinusU = fpsValues[i] - mean;
variance += xMinusU * xMinusU;
}
variance = variance / n;
if (newFrameCount % 20 == 0) {
StringBuffer sb = new StringBuffer();
sb.append("FPS\n");
sb.append(" n ");
sb.append(n);
sb.append('\n');
sb.append(" \u03BC ");
sb.append(Math.round(mean));
sb.append('\n');
sb.append(" \u03C3 ");
sb.append(Math.round(Math.sqrt(variance)));
sb.append('\n');
sb.append(" min ");
sb.append(Math.round(min));
sb.append('\n');
sb.append(" max ");
sb.append(Math.round(max));
sb.append('\n');
newFPSstr = sb.toString();
}
}
// g.setColor(Color.WHITE);
// g.fillRect(50, 50, 50, 20);
// g.setColor(Color.BLACK);
// g.drawString(newFPSstr, 50, 65);
lastFrameTime = currentTime;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactory.createBrokerMenu
Javadoc:
No Javadoc available
Method code:
JMenu createBrokerMenu();
No outgoing methods.
jfreerails.client.top.GUIComponentFactory.createBuildMenu
Javadoc:
No Javadoc available
Method code:
JMenu createBuildMenu();
No outgoing methods.
jfreerails.client.top.GUIComponentFactory.createCashJLabel
Javadoc:
No Javadoc available
Method code:
JLabel createCashJLabel();
No outgoing methods.
jfreerails.client.top.GUIComponentFactory.createDateJLabel
Javadoc:
No Javadoc available
Method code:
JLabel createDateJLabel();
No outgoing methods.
jfreerails.client.top.GUIComponentFactory.createDisplayMenu
Javadoc:
No Javadoc available
Method code:
JMenu createDisplayMenu();
No outgoing methods.
jfreerails.client.top.GUIComponentFactory.createGameMenu
Javadoc:
No Javadoc available
Method code:
JMenu createGameMenu();
No outgoing methods.
jfreerails.client.top.GUIComponentFactory.createHelpMenu
Javadoc:
No Javadoc available
Method code:
JMenu createHelpMenu();
No outgoing methods.
jfreerails.client.top.GUIComponentFactory.createMainMap
Javadoc:
No Javadoc available
Method code:
JScrollPane createMainMap();
No outgoing methods.
jfreerails.client.top.GUIComponentFactory.createOverviewMap
Javadoc:
No Javadoc available
Method code:
JPanel createOverviewMap();
No outgoing methods.
jfreerails.client.top.GUIComponentFactory.createReportsMenu
Javadoc:
No Javadoc available
Method code:
JMenu createReportsMenu();
No outgoing methods.
jfreerails.client.top.GUIComponentFactory.createTrainsJTabPane
Javadoc:
No Javadoc available
Method code:
JTabbedPane createTrainsJTabPane();
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryImpl.countStations
Javadoc:
No Javadoc available
Method code:
private void countStations() {
NonNullElements stations = new NonNullElements(KEY.STATIONS, modelRoot
.getWorld(), modelRoot.getPrincipal());
boolean enabled;
if (stations.size() > 0) {
enabled = true;
} else {
enabled = false;
}
this.trainsJTabPane.setStationTabEnabled(enabled);
this.stationInfoJMenuItem.setEnabled(enabled);
}
Outgoing Methods (calls):
jfreerails.client.top.GUIComponentFactoryImpl.countTrains
Javadoc:
No Javadoc available
Method code:
private void countTrains() {
NonNullElements trains = new NonNullElements(KEY.TRAINS, modelRoot
.getWorld(), modelRoot.getPrincipal());
boolean enabled;
if (trains.size() > 0) {
enabled = true;
} else {
enabled = false;
}
this.trainsJTabPane.setTrainTabEnabled(enabled);
this.trainListJMenuItem.setEnabled(enabled);
this.trainOrdersJMenuItem.setEnabled(enabled);
}
Outgoing Methods (calls):
jfreerails.client.top.GUIComponentFactoryImpl.createBrokerMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createBrokerMenu() {
brokerMenu = new JMenu("Broker");
callBrokerJMenuItem = new JMenuItem("Call Broker");
callBrokerJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showBrokerScreen();
}
});
brokerMenu.add(callBrokerJMenuItem);
return brokerMenu;
}
Outgoing Methods (calls):
jfreerails.client.top.GUIComponentFactoryImpl.createBuildMenu
Javadoc:
/** * Creates and returns the "Build" menu used in the GUI for building operations. * * @return the JMenu instance representing the Build menu */
Method code:
public JMenu createBuildMenu() {
return buildMenu;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryImpl.createCashJLabel
Javadoc:
No Javadoc available
Method code:
public JLabel createCashJLabel() {
return cashjLabel;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryImpl.createClientJFrame
Javadoc:
No Javadoc available
Method code:
public JFrame createClientJFrame(String title) {
clientJFrame.setTitle(title);
return clientJFrame;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryImpl.createDateJLabel
Javadoc:
No Javadoc available
Method code:
public JLabel createDateJLabel() {
return datejLabel;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryImpl.createDisplayMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createDisplayMenu() {
displayMenu = new JMenu("Display");
displayMenu.setMnemonic(68);
trainOrdersJMenuItem = new JMenuItem("Train Orders");
trainOrdersJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showTrainOrders();
}
});
stationInfoJMenuItem = new JMenuItem("Station Info");
stationInfoJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showStationInfo(0);
}
});
trainListJMenuItem = new JMenuItem("Train List");
trainListJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showTrainList();
}
});
displayMenu.add(trainOrdersJMenuItem);
displayMenu.add(stationInfoJMenuItem);
displayMenu.add(trainListJMenuItem);
displayMenu.addSeparator();
// Add menu items to control what gets displayed on the map.
final JCheckBoxMenuItem showCargoMenuItem = new JCheckBoxMenuItem(
"Show cargo at stations", true);
displayMenu.add(showCargoMenuItem);
showCargoMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modelRoot.setProperty(
ModelRoot.Property.SHOW_CARGO_AT_STATIONS, new Boolean(
showCargoMenuItem.isSelected()));
mapViewJComponent.refreshAll();
}
});
final JCheckBoxMenuItem showStationNamesMenuItem = new JCheckBoxMenuItem(
"Show station names", true);
displayMenu.add(showStationNamesMenuItem);
showStationNamesMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modelRoot.setProperty(ModelRoot.Property.SHOW_STATION_NAMES,
new Boolean(showStationNamesMenuItem.isSelected()));
mapViewJComponent.refreshAll();
}
});
final JCheckBoxMenuItem showStationBordersMenuItem = new JCheckBoxMenuItem(
"Show sphere-of-influence around stations", true);
displayMenu.add(showStationBordersMenuItem);
showStationBordersMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modelRoot.setProperty(ModelRoot.Property.SHOW_STATION_BORDERS,
new Boolean(showStationBordersMenuItem.isSelected()));
mapViewJComponent.refreshAll();
}
});
final JCheckBoxMenuItem playSoundsMenuItem = new JCheckBoxMenuItem(
"Play sounds", true);
displayMenu.add(playSoundsMenuItem);
playSoundsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modelRoot.setProperty(ModelRoot.Property.PLAY_SOUNDS,
new Boolean(playSoundsMenuItem.isSelected()));
}
});
;
boolean showFps = Boolean.parseBoolean(System.getProperty("SHOWFPS"));
final JCheckBoxMenuItem showFPSMenuItem = new JCheckBoxMenuItem(
"Show FPS stats", showFps);
displayMenu.add(showFPSMenuItem);
showFPSMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String newValue = String.valueOf(showFPSMenuItem.isSelected());
System.setProperty("SHOWFPS", newValue);
}
});
return displayMenu;
}
Outgoing Methods (calls):
jfreerails.client.top.GUIComponentFactoryImpl.createGameMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createGameMenu() {
sc = actionRoot.getServerControls();
JMenu gameMenu = new JMenu("Game");
gameMenu.setMnemonic(71);
JMenuItem quitJMenuItem = new JMenuItem("Exit Game");
quitJMenuItem.setMnemonic(88);
quitJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
final JMenu newGameJMenu = new JMenu(sc.getNewGameAction());
newGameJMenu.addMenuListener(new MenuListener() {
public void menuCanceled(MenuEvent e) {
}
public void menuDeselected(MenuEvent e) {
}
public void menuSelected(MenuEvent e) {
newGameJMenu.removeAll();
Enumeration<Action> actions = sc.getMapNames().getActions();
while (actions.hasMoreElements()) {
JMenuItem mi = new JMenuItem(actions.nextElement());
newGameJMenu.add(mi);
}
}
});
JMenuItem saveGameJMenuItem = new JMenuItem(sc.getSaveGameAction());
JMenuItem loadGameJMenuItem = new JMenuItem(sc.getLoadGameAction());
// Fix bug 1102806 Newspaper does nothing, so hide it.
// JMenuItem newspaperJMenuItem = new JMenuItem("Newspaper");
// newspaperJMenuItem.setMnemonic(78);
// newspaperJMenuItem.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// dialogueBoxController.showNewspaper("Headline");
// //glassPanel.setVisible(true);
// }
// });
// Set up the game speed sub-menu.
JMenu gameSpeedSubMenu = new JMenu("Game Speed");
ButtonGroup group = new ButtonGroup();
speedActions = sc.getSetTargetTickPerSecondActions();
Enumeration<MappedButtonModel> buttonModels = speedActions
.getButtonModels();
Enumeration<Action> actions = speedActions.getActions();
while (buttonModels.hasMoreElements()) {
JRadioButtonMenuItem mi = new JRadioButtonMenuItem(actions
.nextElement());
mi.setModel(buttonModels.nextElement());
group.add(mi);
gameSpeedSubMenu.add(mi);
}
gameMenu.add(newGameJMenu);
gameMenu.addSeparator();
gameMenu.add(loadGameJMenuItem);
gameMenu.add(saveGameJMenuItem);
gameMenu.addSeparator();
gameMenu.add(gameSpeedSubMenu);
// gameMenu.add(newspaperJMenuItem);
gameMenu.addSeparator();
gameMenu.add(quitJMenuItem);
if (CHEAT) {
/** For testing. */
final ActionListener build200trains = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
WorldIterator wi = new NonNullElements(KEY.STATIONS,
modelRoot.getWorld(), modelRoot.getPrincipal());
if (wi.next()) {
Random randy = new Random();
StationModel station = (StationModel) wi.getElement();
ImList<PlannedTrain> before = station
.getProduction();
int numberOfEngineTypes = modelRoot.getWorld().size(
SKEY.ENGINE_TYPES) - 1;
int numberOfcargoTypes = modelRoot.getWorld().size(
SKEY.CARGO_TYPES) - 1;
PlannedTrain[] temp = new PlannedTrain[200];
for (int i = 0; i < temp.length; i++) {
int engineType = randy.nextInt(numberOfEngineTypes);
int[] wagonTypes = new int[] {
randy.nextInt(numberOfcargoTypes),
randy.nextInt(numberOfcargoTypes),
randy.nextInt(numberOfcargoTypes) };
PlannedTrain plannedTrain = new PlannedTrain(engineType, wagonTypes);
temp[i] = plannedTrain;
}
ImList<PlannedTrain> after = new ImList<PlannedTrain>(temp);
Move m = new ChangeProductionAtEngineShopMove(before,
after, wi.getIndex(), modelRoot.getPrincipal());
modelRoot.doMove(m);
}
}
};
JMenuItem build200TrainsMenuItem = new JMenuItem(
"Build 200 trains!");
build200TrainsMenuItem.addActionListener(build200trains);
gameMenu.add(build200TrainsMenuItem);
}
return gameMenu;
}
Outgoing Methods (calls):
jfreerails.client.top.GUIComponentFactoryImpl.createHelpMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createHelpMenu() {
helpMenu = new javax.swing.JMenu("Help");
JMenuItem about = new JMenuItem("About");
about.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showAbout();
}
});
JMenuItem how2play = new JMenuItem("Getting started");
how2play.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showHow2Play();
}
});
JMenuItem showControls = new JMenuItem("Show game controls");
showControls.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showGameControls();
}
});
JMenuItem showJavaProperties = new JMenuItem("Show Java Properties");
showJavaProperties
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showJavaProperties();
}
});
JMenuItem showReportBug = new JMenuItem("Report Bug");
showReportBug.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showReportBug();
}
});
helpMenu.add(showControls);
helpMenu.add(how2play);
helpMenu.add(showJavaProperties);
helpMenu.add(showReportBug);
helpMenu.add(about);
return helpMenu;
}
Outgoing Methods (calls):
jfreerails.client.top.GUIComponentFactoryImpl.createMainMap
Javadoc:
No Javadoc available
Method code:
public JScrollPane createMainMap() {
return mainMapScrollPane1;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryImpl.createOverviewMap
Javadoc:
No Javadoc available
Method code:
public JPanel createOverviewMap() {
return overviewMapContainer;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryImpl.createReportsMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createReportsMenu() {
reportsMenu = new javax.swing.JMenu("Reports");
JMenuItem incomeStatementJMenuItem = new JMenuItem("Income Statement");
incomeStatementJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showIncomeStatement();
}
});
JMenuItem balanceSheetJMenuItem = new JMenuItem("Balance Sheet");
balanceSheetJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showBalanceSheet();
}
});
leaderBoardJMenuItem = new JMenuItem("Leaderboard");
leaderBoardJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showLeaderBoard();
}
});
networthGraphJMenuItem = new JMenuItem("Networth Graph");
networthGraphJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showNetworthGraph();
}
});
reportsMenu.add(balanceSheetJMenuItem);
reportsMenu.add(incomeStatementJMenuItem);
reportsMenu.add(leaderBoardJMenuItem);
reportsMenu.add(networthGraphJMenuItem);
return reportsMenu;
}
Outgoing Methods (calls):
jfreerails.client.top.GUIComponentFactoryImpl.createTrainsJTabPane
Javadoc:
No Javadoc available
Method code:
public JTabbedPane createTrainsJTabPane() {
return trainsJTabPane;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryImpl.getBuildTrackController
Javadoc:
No Javadoc available
Method code:
public BuildTrackController getBuildTrackController() {
return mainMap.getBuildTrackController();
}
Outgoing Methods (calls):
jfreerails.client.top.GUIComponentFactoryImpl.isSetup
Javadoc:
No Javadoc available
Method code:
public boolean isSetup() {
return isSetup;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryImpl.itemAdded
Javadoc:
/** * Handles the addition of an item, updating the count of trains or stations * based on the provided key and principal. This method is invoked when an item * is added to the model, and it triggers the corresponding count method * (countTrains() or countStations()) if the key matches and the principal * matches the model's principal. * * @param key The type of item being added (e.g., TRAINS or STATIONS). * @param index The index at which the item was added. * @param principal The principal associated with the item addition. */
Method code:
public void itemAdded(KEY key, int index, FreerailsPrincipal principal) {
boolean rightPrincipal = principal
.equals(this.modelRoot.getPrincipal());
if (KEY.TRAINS == key && rightPrincipal) {
countTrains();
} else if (KEY.STATIONS == key && rightPrincipal) {
countStations();
}
}
Outgoing Methods (calls):
jfreerails.client.top.GUIComponentFactoryImpl.itemRemoved
Javadoc:
No Javadoc available
Method code:
public void itemRemoved(KEY key, int index, FreerailsPrincipal principal) {
// do nothing
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryImpl.listUpdated
Javadoc:
No Javadoc available
Method code:
public void listUpdated(KEY key, int index, FreerailsPrincipal principal) {
boolean rightPrincipal = principal
.equals(this.modelRoot.getPrincipal());
if (KEY.TRAINS == key && rightPrincipal) {
countTrains();
} else if (KEY.STATIONS == key && rightPrincipal) {
countStations();
}
}
Outgoing Methods (calls):
jfreerails.client.top.GUIComponentFactoryImpl.setup
Javadoc:
/** * Called when a new game is started or a game is loaded. * <p> * <b>Be extremely careful with the references of objects allocated in this * method to avoid memory leaks - see bug 967677 (OutOfMemoryError after * starting several new games). </b> * </p> */
Method code:
/**
* Called when a new game is started or a game is loaded.
* <p>
* <b>Be extremely careful with the references of objects allocated in this
* method to avoid memory leaks - see bug 967677 (OutOfMemoryError after
* starting several new games). </b>
* </p>
*/
public void setup(RenderersRoot vl, ReadOnlyWorld w) throws IOException {
/*
* Set the cursor position. The initial cursor position is 0,0. However,
* if a game is loaded or a new game is started and the map size is the
* same as the last map size, then the cursor should take the position
* it had on the last map.
*/
ImPoint cursorPosition = new ImPoint(0, 0);
if (null != world) {
if (w.getMapWidth() == world.getMapWidth()
&& w.getMapHeight() == world.getMapHeight()) {
cursorPosition = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.CURSOR_POSITION);
}
}
renderers = vl;
world = w;
modelRoot.addMapListener(this);
modelRoot.addListListener(this);
if (!vl.validate(world)) {
throw new IllegalArgumentException("The specified"
+ " RenderersRoot are not compatible with the clients"
+ "world!");
}
// create the main and overview maps
mainMap = new DetailMapRenderer(world, renderers, modelRoot);
TrainRenderer trainRenderer = mainMap.getTrainRenderer();
Dimension maxSize = new Dimension(200, 200);
overviewMap = ZoomedOutMapRenderer.getInstance(world, maxSize);
stationTypesPopup.setup(modelRoot, actionRoot, mainMap
.getStationRadius());
mapViewJComponent
.setup(mainMap, modelRoot, renderers);
// setup the the main and overview map JComponents
dialogueBoxController.setDefaultFocusOwner(mapViewJComponent);
userInputOnMapController.setup(mapViewJComponent, actionRoot
.getTrackMoveProducer(), stationTypesPopup, this.modelRoot,
dialogueBoxController, mapViewJComponent.getMapCursor(),
getBuildTrackController(), trainRenderer);
buildMenu.setup(actionRoot);
mainMapScrollPane1.setViewportView(this.mapViewJComponent);
((OverviewMapJComponent) overviewMapContainer).setup(overviewMap);
datejLabel.setup(modelRoot, vl, null);
cashjLabel.setup(modelRoot, vl, null);
trainsJTabPane.setup(actionRoot, vl, modelRoot);
dialogueBoxController.setup(modelRoot, vl);
StationPlacementCursor.wireUp(actionRoot, mainMap.getStationRadius(),
mapViewJComponent);
int gameSpeed = ((GameSpeed) world.get(ITEM.GAME_SPEED)).getSpeed();
/* Set the selected game speed radio button. */
String actionName = actionRoot.getServerControls().getGameSpeedDesc(
gameSpeed);
speedActions.setSelectedItem(actionName);
userMessageGenerator.logSpeed();
/*
* Count stations and trains to determine if we need to display the
* station and train menu items and tabs.3
*/
countStations();
countTrains();
String name = modelRoot.getPrincipal().getName();
String serverDetails = (String) modelRoot
.getProperty(ModelRoot.Property.SERVER);
String frameTitle;
if (serverDetails.equals(LocalConnection.SERVER_IN_SAME_JVM)) {
frameTitle = name + " - Freerails";
} else {
frameTitle = name + " - " + serverDetails + " - Freerails";
}
clientJFrame.setTitle(frameTitle);
isSetup = true;
modelRoot.setProperty(ModelRoot.Property.CURSOR_POSITION,
cursorPosition);
mapViewJComponent.requestFocus();
}
Outgoing Methods (calls):
jfreerails.client.top.GUIComponentFactoryImpl.tilesChanged
Javadoc:
/** * Listens for changes on the map, for instance when track is built, and * refreshes the map views. */
Method code:
/**
* Listens for changes on the map, for instance when track is built, and
* refreshes the map views.
*/
public void tilesChanged(Rectangle tilesChanged) {
logger.fine("TilesChanged = " + tilesChanged);
// If lots of tiles have changed, do a complete refresh.
int size = tilesChanged.width * tilesChanged.height;
if (size > 100) {
mainMap.refreshAll();
overviewMap.refreshAll();
} else {
Point tile = new Point();
// Fix for bug 967673 (Crash when building track close to edge of
// map).
Rectangle mapRect = new Rectangle(0, 0, world.getMapWidth(), world
.getMapHeight());
tilesChanged = tilesChanged.intersection(mapRect);
for (tile.x = tilesChanged.x; tile.x < (tilesChanged.x + tilesChanged.width); tile.x++) {
for (tile.y = tilesChanged.y; tile.y < (tilesChanged.y + tilesChanged.height); tile.y++) {
mainMap.refreshTile(tile.x, tile.y);
overviewMap.refreshTile(tile.x, tile.y);
}
}
}
}
Outgoing Methods (calls):
jfreerails.client.top.GUIComponentFactoryTestImpl.createBrokerMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createBrokerMenu() {
return brokerMenu;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryTestImpl.createBuildMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createBuildMenu() {
return buildMenu;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryTestImpl.createCashJLabel
Javadoc:
No Javadoc available
Method code:
public JLabel createCashJLabel() {
return cashjLabel;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryTestImpl.createDateJLabel
Javadoc:
No Javadoc available
Method code:
public JLabel createDateJLabel() {
return datejLabel;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryTestImpl.createDisplayMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createDisplayMenu() {
return displayMenu;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryTestImpl.createGameMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createGameMenu() {
return gameMenu;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryTestImpl.createHelpMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createHelpMenu() {
return helpMenu;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryTestImpl.createMainMap
Javadoc:
No Javadoc available
Method code:
public JScrollPane createMainMap() {
return mainMapView;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryTestImpl.createOverviewMap
Javadoc:
No Javadoc available
Method code:
public JPanel createOverviewMap() {
return mapOverview;
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryTestImpl.createReportsMenu
Javadoc:
No Javadoc available
Method code:
public JMenu createReportsMenu() {
return new JMenu("Reports");
}
No outgoing methods.
jfreerails.client.top.GUIComponentFactoryTestImpl.createTrainsJTabPane
Javadoc:
No Javadoc available
Method code:
public JTabbedPane createTrainsJTabPane() {
return trainsJPanel;
}
No outgoing methods.
jfreerails.client.top.GameLoop.run
Javadoc:
No Javadoc available
Method code:
public void run() {
try {
SynchronizedEventQueue.use();
RepaintManagerForActiveRendering.addJFrame(screenHandler.frame);
RepaintManagerForActiveRendering.setAsCurrentManager();
if (!screenHandler.isInUse()) {
screenHandler.apply();
}
gameNotDone = true;
fPScounter = new FPScounter();
/*
* Reduce this threads priority to avoid starvation of the input
* thread on Windows.
*/
try {
Thread.currentThread().setPriority(Thread.NORM_PRIORITY - 1);
} catch (SecurityException e) {
logger.warning("Couldn't lower priority of redraw thread");
}
while (true) {
// stats.record();
frameStartTime = System.currentTimeMillis();
/*
* Flush all redraws in the underlying toolkit. This reduces X11
* lag when there isn't much happening, but is expensive under
* Windows
*/
Toolkit.getDefaultToolkit().sync();
synchronized (SynchronizedEventQueue.MUTEX) {
if (!gameNotDone) {
SynchronizedEventQueue.MUTEX.notify();
break;
}
for (int i = 0; i < model.length; i++) {
model[i].update();
}
if (!screenHandler.isMinimised()) {
if (screenHandler.isInUse()) {
boolean contentsRestored = false;
do {
Graphics g = screenHandler.getDrawGraphics();
try {
screenHandler.frame.paintComponents(g);
boolean showFps = Boolean
.parseBoolean(System
.getProperty("SHOWFPS"));
if (showFps) {
fPScounter.drawFPS((Graphics2D) g);
}
} catch (RuntimeException re) {
/*
* We are not expecting a RuntimeException
* here. If something goes wrong, lets kill
* the game straight away to avoid
* hard-to-track-down bugs.
*/
ReportBugTextGenerator
.unexpectedException(re);
} finally {
g.dispose();
}
contentsRestored = screenHandler
.contentsRestored();
} while (contentsRestored);
screenHandler.swapScreens();
fPScounter.updateFPSCounter();
}
}
}
if (screenHandler.isMinimised()) {
try {
// The window is minimised so we don't need to keep
// updating.
Thread.sleep(200);
} catch (Exception e) {
// do nothing.
}
} else if (LIMIT_FRAME_RATE) {
long deltatime = System.currentTimeMillis()
- frameStartTime;
while (deltatime < (1000 / TARGET_FPS)) {
try {
long sleeptime = (1000 / TARGET_FPS) - deltatime;
Thread.sleep(sleeptime);
} catch (Exception e) {
e.printStackTrace();
}
deltatime = System.currentTimeMillis() - frameStartTime;
}
}
// remove all events from a event queue (max 5ms)
long startEventWaitTime = System.currentTimeMillis() + 4;
while (SynchronizedEventQueue.getInstance().peekEvent() != null) {
// we have events
Thread.yield();
if (startEventWaitTime < System.currentTimeMillis()) {
break;
}
}
}
/* signal that we are done */
synchronized (loopMonitor) {
loopMonitor.notify();
}
} catch (Exception e) {
ReportBugTextGenerator.unexpectedException(e);
}
}
Outgoing Methods (calls):
jfreerails.client.top.QuickRGBTileRendererList.createImageFor
Javadoc:
No Javadoc available
Method code:
public static Image createImageFor(TerrainType t) {
Image image = defaultConfiguration.createCompatibleImage(
Constants.TILE_SIZE, Constants.TILE_SIZE);
Color c = new Color(t.getRGB());
Graphics g = image.getGraphics();
g.setColor(c);
g.fillRect(0, 0, Constants.TILE_SIZE, Constants.TILE_SIZE);
g.dispose();
return image;
}
Outgoing Methods (calls):
jfreerails.client.top.QuickRGBTileRendererList.getTileViewWithNumber
Javadoc:
No Javadoc available
Method code:
public TileRenderer getTileViewWithNumber(int i) {
throw new UnsupportedOperationException();
}
No outgoing methods.
jfreerails.client.top.QuickRGBTileRendererList.getTileViewWithRGBValue
Javadoc:
No Javadoc available
Method code:
public TileRenderer getTileViewWithRGBValue(int rgb) {
Integer i = rgb2index.get(new Integer(rgb));
this.simpleTileRenderer.setImage(images[i.intValue()]);
return simpleTileRenderer;
}
Outgoing Methods (calls):
jfreerails.client.top.QuickRGBTileRendererList.validate
Javadoc:
No Javadoc available
Method code:
public boolean validate(ReadOnlyWorld world) {
return true;
}
No outgoing methods.
jfreerails.client.top.RenderersRootImpl.getEngineImages
Javadoc:
No Javadoc available
Method code:
public TrainImages getEngineImages(int type) {
return engineImages.get(type);
}
No outgoing methods.
jfreerails.client.top.RenderersRootImpl.getImage
Javadoc:
No Javadoc available
Method code:
public Image getImage(String relativeFilename) throws IOException {
return imageManager.getImage(relativeFilename);
}
Outgoing Methods (calls):
jfreerails.client.top.RenderersRootImpl.getImageManager
Javadoc:
No Javadoc available
Method code:
public ImageManager getImageManager() {
return imageManager;
}
No outgoing methods.
jfreerails.client.top.RenderersRootImpl.getScaledImage
Javadoc:
No Javadoc available
Method code:
public Image getScaledImage(String relativeFilename, int height) throws IOException {
return imageManager.getScaledImage(relativeFilename, height);
}
Outgoing Methods (calls):
jfreerails.client.top.RenderersRootImpl.getTileViewList
Javadoc:
No Javadoc available
Method code:
public TileRendererList getTileViewList() {
return this.tiles;
}
No outgoing methods.
jfreerails.client.top.RenderersRootImpl.getTileViewWithNumber
Javadoc:
No Javadoc available
Method code:
public TileRenderer getTileViewWithNumber(int i) {
return tiles.getTileViewWithNumber(i);
}
Outgoing Methods (calls):
jfreerails.client.top.RenderersRootImpl.getTrackPieceView
Javadoc:
No Javadoc available
Method code:
public TrackPieceRenderer getTrackPieceView(int i) {
return trackPieceViewList.getTrackPieceView(i);
}
Outgoing Methods (calls):
jfreerails.client.top.RenderersRootImpl.getTrackPieceViewList
Javadoc:
No Javadoc available
Method code:
public TrackPieceRendererList getTrackPieceViewList() {
return this.trackPieceViewList;
}
No outgoing methods.
jfreerails.client.top.RenderersRootImpl.getWagonImages
Javadoc:
No Javadoc available
Method code:
public TrainImages getWagonImages(int type) {
return wagonImages.get(type);
}
No outgoing methods.
jfreerails.client.top.RenderersRootImpl.loadNewTileViewList
Javadoc:
No Javadoc available
Method code:
private TileRendererList loadNewTileViewList(ReadOnlyWorld w,
FreerailsProgressMonitor pm) throws IOException {
ArrayList<TileRenderer> tileRenderers = new ArrayList<TileRenderer>();
// Setup progress monitor..
int numberOfTypes = w.size(SKEY.TERRAIN_TYPES);
pm.nextStep(numberOfTypes);
int progress = 0;
pm.setValue(progress);
for (int i = 0; i < numberOfTypes; i++) {
TerrainType t = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
int[] typesTreatedAsTheSame = new int[] { i };
TileRenderer tr = null;
pm.setValue(++progress);
try {
// XXX hack to make rivers flow into ocean and habours & occean
// treat habours as the same type.
TerrainType.Category thisTerrainCategory = t.getCategory();
if (thisTerrainCategory.equals(TerrainType.Category.River)
|| thisTerrainCategory
.equals(TerrainType.Category.Ocean)) {
// Count number of types with category "water"
int count = 0;
for (int j = 0; j < numberOfTypes; j++) {
TerrainType t2 = (TerrainType) w.get(
SKEY.TERRAIN_TYPES, j);
TerrainType.Category terrainCategory = t2.getCategory();
if (terrainCategory.equals(TerrainType.Category.Ocean)
|| terrainCategory.equals(thisTerrainCategory)) {
count++;
}
}
typesTreatedAsTheSame = new int[count];
count = 0;
for (int j = 0; j < numberOfTypes; j++) {
TerrainType t2 = (TerrainType) w.get(
SKEY.TERRAIN_TYPES, j);
TerrainType.Category terrainCategory = t2.getCategory();
if (terrainCategory.equals(TerrainType.Category.Ocean)
|| terrainCategory.equals(thisTerrainCategory)) {
typesTreatedAsTheSame[count] = j;
count++;
}
}
}
tr = new RiverStyleTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io) {
}
try {
tr = new ForestStyleTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io) {
}
try {
tr = new ChequeredTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io) {
}
try {
tr = new StandardTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io) {
// If the image is missing, we generate it.
logger
.warning("No tile renderer for "
+ t.getTerrainTypeName());
String filename = StandardTileRenderer.generateFilename(t
.getTerrainTypeName());
Image image = QuickRGBTileRendererList.createImageFor(t);
imageManager.setImage(filename, image);
// generatedImages.setImage(filename, image);
try {
tr = new StandardTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io2) {
io2.printStackTrace();
throw new IllegalStateException();
}
}
}
// XXXX add special tile renderer for habours
TileRenderer oceanTileRenderer = null;
for (int j = 0; j < numberOfTypes; j++) {
TerrainType t2 = (TerrainType) w.get(SKEY.TERRAIN_TYPES, j);
String terrainName = t2.getTerrainTypeName();
if (terrainName.equalsIgnoreCase("Ocean")) {
oceanTileRenderer = tileRenderers.get(j);
break;
}
}
for (int j = 0; j < numberOfTypes; j++) {
TerrainType t2 = (TerrainType) w.get(SKEY.TERRAIN_TYPES, j);
String terrainName = t2.getTerrainTypeName();
if (terrainName.equalsIgnoreCase("Harbour")) {
TerrainType t = (TerrainType) w.get(SKEY.TERRAIN_TYPES, j);
TileRenderer tr = new SpecialTileRenderer(imageManager,
new int[] { j }, t, oceanTileRenderer);
tileRenderers.set(j, tr);
break;
}
}
return new TileRendererListImpl(tileRenderers);
}
Outgoing Methods (calls):
jfreerails.client.top.RenderersRootImpl.loadTrackViews
Javadoc:
No Javadoc available
Method code:
private TrackPieceRendererList loadTrackViews(ReadOnlyWorld w,
FreerailsProgressMonitor pm) throws IOException {
return new TrackPieceRendererList(w, imageManager, pm);
}
No outgoing methods.
jfreerails.client.top.RenderersRootImpl.loadTrainImages
Javadoc:
No Javadoc available
Method code:
private void loadTrainImages(ReadOnlyWorld w, FreerailsProgressMonitor pm)
throws IOException {
// Setup progress monitor..
final int numberOfWagonTypes = w.size(SKEY.CARGO_TYPES);
final int numberOfEngineTypes = w.size(SKEY.ENGINE_TYPES);
pm.nextStep(numberOfWagonTypes + numberOfEngineTypes);
int progress = 0;
pm.setValue(progress);
//Load wagon images.
for (int i = 0; i < numberOfWagonTypes; i++) {
CargoType cargoType = (CargoType) w.get(SKEY.CARGO_TYPES, i);
String name = cargoType.getName();
TrainImages ti = new TrainImages(imageManager, name);
wagonImages.add(ti);
pm.setValue(++progress);
}
//Load engine images
for (int i = 0; i < numberOfEngineTypes; i++) {
EngineType engineType = (EngineType) w.get(SKEY.ENGINE_TYPES, i);
String engineTypeName = engineType
.getEngineTypeName();
TrainImages ti = new TrainImages(imageManager, engineTypeName);
engineImages.add(ti);
pm.setValue(++progress);
}
}
Outgoing Methods (calls):
jfreerails.client.top.RenderersRootImpl.preloadSounds
Javadoc:
No Javadoc available
Method code:
private void preloadSounds(FreerailsProgressMonitor pm) {
// Pre-load sounds..
String[] soundsFiles = { "/jfreerails/client/sounds/buildtrack.wav",
"/jfreerails/client/sounds/cash.wav",
"/jfreerails/client/sounds/removetrack.wav",
"/jfreerails/client/sounds/whistle.wav" };
pm.nextStep(soundsFiles.length);
SoundManager sm = SoundManager.getSoundManager();
for (int i = 0; i < soundsFiles.length; i++) {
try {
sm.addClip(soundsFiles[i]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pm.setValue(i + 1);
}
}
Outgoing Methods (calls):
jfreerails.client.top.RenderersRootImpl.validate
Javadoc:
No Javadoc available
Method code:
public boolean validate(ReadOnlyWorld w) {
boolean okSoFar = true;
if (!this.tiles.validate(w)) {
okSoFar = false;
}
if (!this.trackPieceViewList.validate(w)) {
okSoFar = false;
}
return okSoFar;
}
Outgoing Methods (calls):
jfreerails.client.top.SimpleTileRenderer.dumpImages
Javadoc:
No Javadoc available
Method code:
public void dumpImages(ImageManager imageManager) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
No outgoing methods.
jfreerails.client.top.SimpleTileRenderer.getDefaultIcon
Javadoc:
No Javadoc available
Method code:
public Image getDefaultIcon() {
return i;
}
No outgoing methods.
jfreerails.client.top.SimpleTileRenderer.renderTile
Javadoc:
/** * Renders a tile at the specified screen coordinates using the given world coordinates. * * @param g The Graphics object used for rendering. * @param renderX The x-coordinate on the screen where the tile is rendered. * @param renderY The y-coordinate on the screen where the tile is rendered. * @param mapX The x-coordinate in the world map corresponding to the tile. * @param mapY The y-Coordinate in the world map corresponding to the tile. * @param w The ReadOnlyWorld instance providing tile data or image information. */
Method code:
public void renderTile(Graphics g, int renderX, int renderY, int mapX,
int mapY, ReadOnlyWorld w) {
g.drawImage(i, renderX, renderY, null);
}
No outgoing methods.
jfreerails.client.top.SimpleTileRenderer.setImage
Javadoc:
No Javadoc available
Method code:
public void setImage(Image i) {
this.i = i;
}
No outgoing methods.
jfreerails.client.top.StationBuildMenuItem.configurePropertiesFromAction
Javadoc:
No Javadoc available
Method code:
@Override
public void configurePropertiesFromAction(Action a) {
super.configurePropertiesFromAction(a);
}
No outgoing methods.
jfreerails.client.top.StationTypesPopup.canBuiltStationHere
Javadoc:
No Javadoc available
Method code:
public boolean canBuiltStationHere(Point p) {
stationBuildModel.getStationBuildAction().putValue(
StationBuildModel.StationBuildAction.STATION_POSITION_KEY, p);
FreerailsTile tile = (FreerailsTile) modelRoot.getWorld().getTile(p.x,
p.y);
return tile.hasTrack();
}
Outgoing Methods (calls):
jfreerails.client.top.StationTypesPopup.setVisible
Javadoc:
No Javadoc available
Method code:
@Override
public void setVisible(boolean b) {
// If this popup is visible, we don't want the station's position to
// follow the mouse.
stationBuildModel.setPositionFollowsMouse(!b);
super.setVisible(b);
}
Outgoing Methods (calls):
jfreerails.client.top.StationTypesPopup.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot mr, ActionRoot actionRoot,
StationRadiusRenderer srr) {
modelRoot = mr;
stationBuildModel = actionRoot.getStationBuildModel();
stationRadiusRenderer = srr;
this.removeAll();
this.removePopupMenuListener(popupMenuListener);
popupMenuListener = new PopupMenuListener() {
public void popupMenuCanceled(PopupMenuEvent e) {
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
stationRadiusRenderer.hide();
stationBuildModel.getStationCancelAction().actionPerformed(
new ActionEvent(StationTypesPopup.this,
ActionEvent.ACTION_PERFORMED, ""));
}
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
stationRadiusRenderer.setPosition(tileToBuildStationOn.x,
tileToBuildStationOn.y);
stationBuildModel
.getStationBuildAction()
.putValue(
StationBuildModel.StationBuildAction.STATION_POSITION_KEY,
tileToBuildStationOn);
}
};
this.addPopupMenuListener(popupMenuListener);
final Action[] stationChooseActions = stationBuildModel
.getStationChooseActions();
for (int i = 0; i < stationChooseActions.length; i++) {
final StationBuildMenuItem rbMenuItem = new StationBuildMenuItem();
final int index = i;
rbMenuItem.configurePropertiesFromAction(stationChooseActions[i]);
rbMenuItem.setIcon(null);
// Show the relevant station radius when the station type's
// menu item gets focus.
rbMenuItem.addChangeListener(new ChangeListener() {
private boolean armed = false;
public void stateChanged(ChangeEvent e) {
if (rbMenuItem.isArmed() && (rbMenuItem.isArmed() != armed)) {
stationChooseActions[index]
.actionPerformed(new ActionEvent(rbMenuItem,
ActionEvent.ACTION_PERFORMED, ""));
}
armed = rbMenuItem.isArmed();
}
});
rbMenuItem.addActionListener(stationBuildModel
.getStationBuildAction());
add(rbMenuItem);
}
stationBuildModel.getStationBuildAction().addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if (e
.getPropertyName()
.equals(
StationBuildModel.StationBuildAction.STATION_RADIUS_KEY)) {
int newRadius = ((Integer) e.getNewValue())
.intValue();
stationRadiusRenderer.setRadius(newRadius);
}
if (stationBuildModel.getStationBuildAction()
.isEnabled()) {
stationRadiusRenderer.show();
} else {
stationRadiusRenderer.hide();
}
}
});
}
Outgoing Methods (calls):
jfreerails.client.top.StationTypesPopup.showMenu
Javadoc:
No Javadoc available
Method code:
public void showMenu(Component invoker, int x, int y, Point tile) {
tileToBuildStationOn = tile;
super.show(invoker, x, y);
}
No outgoing methods.
jfreerails.client.top.SynchronizedEventQueue.dispatchEvent
Javadoc:
No Javadoc available
Method code:
@Override
protected void dispatchEvent(AWTEvent aEvent) {
synchronized (MUTEX) {
try {
super.dispatchEvent(aEvent);
} catch (Exception e) {
/*
* If something goes wrong, lets kill the game straight away to
* avoid hard-to-track-down bugs.
*/
ReportBugTextGenerator.unexpectedException(e);
}
}
}
Outgoing Methods (calls):
jfreerails.client.top.SynchronizedEventQueue.getInstance
Javadoc:
No Javadoc available
Method code:
public static SynchronizedEventQueue getInstance() {
return instance;
}
No outgoing methods.
jfreerails.client.top.SynchronizedEventQueue.use
Javadoc:
No Javadoc available
Method code:
public static synchronized void use() {
if (!alreadyInUse) {
/* set up the synchronized event queue */
EventQueue eventQueue = Toolkit.getDefaultToolkit()
.getSystemEventQueue();
eventQueue.push(instance);
alreadyInUse = true;
}
}
No outgoing methods.
jfreerails.client.top.UserInputOnMapController.cancelProposedBuild
Javadoc:
No Javadoc available
Method code:
private void cancelProposedBuild() {
ignoreDragging = true;
buildTrack.hide();
StationBuildModel sbm = actionRoot.getStationBuildModel();
sbm.getStationCancelAction().actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
setIgnoreKeyEvents(false);
}
Outgoing Methods (calls):
jfreerails.client.top.UserInputOnMapController.cursorJumped
Javadoc:
No Javadoc available
Method code:
private void cursorJumped(ImPoint to) {
// if (trackBuilder.getTrackBuilderMode() ==
// TrackMoveProducer.UPGRADE_TRACK) {
// MoveStatus ms = trackBuilder.upgradeTrack(to);
//
// if (ms.ok) {
// setCursorMessage("");
// playAppropriateSound();
// } else {
// setCursorMessage(ms.message);
// }
// }
}
No outgoing methods.
jfreerails.client.top.UserInputOnMapController.cursorOneTileMove
Javadoc:
No Javadoc available
Method code:
private void cursorOneTileMove(ImPoint oldPosition, Step vector) {
boolean b = (modelRoot.getProperty(ModelRoot.Property.CURSOR_MODE) == ModelRoot.Value.BUILD_TRACK_CURSOR_MODE);
if (null != trackBuilder && b) {
trackBuilder.setBuildTrackStrategy(getBts());
MoveStatus ms = trackBuilder.buildTrack(oldPosition, vector);
if (ms.ok) {
setCursorMessage("");
playAppropriateSound();
} else {
setCursorMessage(ms.message);
}
} else {
logger.warning("No track builder available!");
}
}
Outgoing Methods (calls):
jfreerails.client.top.UserInputOnMapController.getBts
Javadoc:
No Javadoc available
Method code:
private BuildTrackStrategy getBts() {
BuildTrackStrategy bts = (BuildTrackStrategy) modelRoot
.getProperty(ModelRoot.Property.BUILD_TRACK_STRATEGY);
if (null == bts) {
throw new NullPointerException();
}
return bts;
}
Outgoing Methods (calls):
jfreerails.client.top.UserInputOnMapController.getCursorPosition
Javadoc:
/** * Retrieves the current cursor position from the model. * This method fetches the {@code CURSOR_POSITION} property from the model root, * returning it as an {@code ImPoint}. If the property is {@code null}, a default * {@code ImPoint} instance is returned instead. * * @return the cursor position as an {@code ImPoint}, or a default instance if the property is null */
Method code:
private ImPoint getCursorPosition() {
ImPoint point = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.CURSOR_POSITION);
// Check for null
point = null == point ? new ImPoint() : point;
return point;
}
Outgoing Methods (calls):
jfreerails.client.top.UserInputOnMapController.isIgnoreKeyEvents
Javadoc:
No Javadoc available
Method code:
private boolean isIgnoreKeyEvents() {
Boolean b = (Boolean) modelRoot.getProperty(Property.IGNORE_KEY_EVENTS);
return b.booleanValue();
}
Outgoing Methods (calls):
jfreerails.client.top.UserInputOnMapController.keyPressed
Javadoc:
No Javadoc available
Method code:
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (isIgnoreKeyEvents()) {
if (keyCode == KeyEvent.VK_ESCAPE) {
setIgnoreKeyEvents(false);
} else {
return;
}
}
ImPoint cursorPosition = getCursorPosition();
switch (keyCode) {
case KeyEvent.VK_NUMPAD1:
moveCursorOneTile(Step.SOUTH_WEST);
break;
case KeyEvent.VK_NUMPAD2:
moveCursorOneTile(Step.SOUTH);
break;
// @SonnyZ
case KeyEvent.VK_DOWN:
if (e.getModifiers() == 2) {
moveCursorOneTile(Step.SOUTH);
}
break;
// --
case KeyEvent.VK_NUMPAD3:
moveCursorOneTile(Step.SOUTH_EAST);
break;
case KeyEvent.VK_NUMPAD4:
moveCursorOneTile(Step.WEST);
break;
// @SonnyZ
case KeyEvent.VK_LEFT:
if (e.getModifiers() == 2) {
moveCursorOneTile(Step.WEST);
}
break;
// --
case KeyEvent.VK_NUMPAD6:
moveCursorOneTile(Step.EAST);
break;
// @SonnyZ
case KeyEvent.VK_RIGHT:
if (e.getModifiers() == 2) {
moveCursorOneTile(Step.EAST);
}
break;
// --
case KeyEvent.VK_NUMPAD7:
moveCursorOneTile(Step.NORTH_WEST);
break;
case KeyEvent.VK_NUMPAD8:
moveCursorOneTile(Step.NORTH);
break;
// @SonnyZ
case KeyEvent.VK_UP:
if (e.getModifiers() == 2) {
moveCursorOneTile(Step.NORTH);
}
break;
// --
case KeyEvent.VK_NUMPAD9:
moveCursorOneTile(Step.NORTH_EAST);
break;
case KeyEvent.VK_F8: {
// Check whether we can built a station here before proceeding.
if (stationTypesPopup.canBuiltStationHere(cursorPosition.toPoint())) {
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
int x = cursorPosition.x * tileSize.width;
int y = cursorPosition.y * tileSize.height;
stationTypesPopup.showMenu(mapView, x, y, cursorPosition
.toPoint());
} else {
modelRoot.setProperty(Property.QUICK_MESSAGE, "Can't"
+ " build station here!");
}
break;
}
case KeyEvent.VK_BACK_SPACE:
logger.info("Undo building track currently not implemented.");
//
// MoveStatus ms = trackBuilder.undoLastTrackMove();
//
// if (!ms.isOk()) {
// setCursorMessage(ms.message);
// }
break;
case KeyEvent.VK_I: {
dialogueBoxController.showStationOrTerrainInfo(cursorPosition.x,
cursorPosition.y);
break;
}
case KeyEvent.VK_C: {
mapView.centerOnTile(cursorPosition.toPoint());
break;
}
case KeyEvent.VK_B: {
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
int x = cursorPosition.x * tileSize.width;
int y = cursorPosition.y * tileSize.height;
buildIndustryJPopupMenu.setCursorLocation(cursorPosition.toPoint());
buildIndustryJPopupMenu.show(mapView, x, y);
break;
}
case KeyEvent.VK_ESCAPE: {
cancelProposedBuild();
break;
}
// @author SonnyZ
case KeyEvent.VK_X: {
// modelRoot.setProperty(Property.QUICK_MESSAGE, keyCode + " was
// pressed!");
dialogueBoxController.showExitDialog();
break;
}
// @SonnyZ
case KeyEvent.VK_S: {
if (e.getModifiers() == 2) {
ServerControlModel cont = actionRoot.getServerControls();
// String name = JOptionPane.showInputDialog(null, "Saved Game
// Name:","Save
// Game",JOptionPane.QUESTION_MESSAGE,null,null,modelRoot.getPrincipal().getName()).toString();
// modelRoot.setProperty(Property.QUICK_MESSAGE, name);
cont.getSaveGameAction().actionPerformed(null);
}
break;
}
// @SonnyZ
case KeyEvent.VK_L: {
if (e.getModifiers() == 2) {
ServerControlModel cont = actionRoot.getServerControls();
cont.getLoadGameAction().actionPerformed(null);
}
break;
}
// @SonnyZ
case KeyEvent.VK_M: {
// if the screen is not clicked after the broker screen is closed
// and 'M' is pressed
// again, the broker screen will never show up again.
dialogueBoxController.showBrokerScreen();
break;
}
case KeyEvent.VK_F12: {
System.out.println("Disable keyboard input!");
setIgnoreKeyEvents(true);
break;
}
}
}
Outgoing Methods (calls):
jfreerails.client.top.UserInputOnMapController.legalRectangleContains
Javadoc:
/** * Checks whether specified point is in legal rectangle. * * @param tryThisPoint ImPoint * @return boolean */
Method code:
/**
* Checks whether specified point is in legal rectangle.
*
* @param tryThisPoint ImPoint
* @return boolean
*/
private boolean legalRectangleContains(ImPoint tryThisPoint) {
ReadOnlyWorld world = modelRoot.getWorld();
int width = world.getMapWidth();
int height = world.getMapHeight();
Rectangle legalRectangle = new Rectangle(0, 0, width, height);
return legalRectangle.contains(tryThisPoint.toPoint());
}
Outgoing Methods (calls):
jfreerails.client.top.UserInputOnMapController.moveCursorJump
Javadoc:
No Javadoc available
Method code:
private void moveCursorJump(ImPoint tryThisPoint) {
setCursorMessage("");
if (legalRectangleContains(tryThisPoint)) {
setCursorPosition(tryThisPoint);
cursorJumped(tryThisPoint);
} else {
this.setCursorMessage("Illegal cursor position!");
}
}
Outgoing Methods (calls):
jfreerails.client.top.UserInputOnMapController.moveCursorOneTile
Javadoc:
No Javadoc available
Method code:
private void moveCursorOneTile(Step v) {
setCursorMessage(null);
ImPoint cursorMapPosition = this.getCursorPosition();
ImPoint tryThisPoint = new ImPoint(cursorMapPosition.x + v.getDx(),
cursorMapPosition.y + v.getDy());
/* Move the cursor. */
if (legalRectangleContains(tryThisPoint)) {
setCursorPosition(tryThisPoint);
cursorOneTileMove(cursorMapPosition, v);
} else {
this.setCursorMessage("Illegal cursor position!");
}
}
Outgoing Methods (calls):
jfreerails.client.top.UserInputOnMapController.playAppropriateSound
Javadoc:
No Javadoc available
Method code:
private void playAppropriateSound() {
switch (trackBuilder.getTrackBuilderMode()) {
case BUILD_TRACK:
case UPGRADE_TRACK:
soundManager.playSound(JFREERAILS_CLIENT_SOUNDS_BUILDTRACK_WAV, 0);
break;
case REMOVE_TRACK:
soundManager.playSound("/jfreerails/client/sounds/removetrack.wav",
0);
break;
default:
// do nothing
}
}
Outgoing Methods (calls):
jfreerails.client.top.UserInputOnMapController.setCursorMessage
Javadoc:
No Javadoc available
Method code:
private void setCursorMessage(String s) {
modelRoot.setProperty(Property.CURSOR_MESSAGE, s);
}
Outgoing Methods (calls):
jfreerails.client.top.UserInputOnMapController.setCursorPosition
Javadoc:
No Javadoc available
Method code:
private void setCursorPosition(ImPoint p) {
// Make a defensive copy.
ImPoint point = p;
modelRoot.setProperty(Property.CURSOR_POSITION, point);
}
Outgoing Methods (calls):
jfreerails.client.top.UserInputOnMapController.setIgnoreKeyEvents
Javadoc:
No Javadoc available
Method code:
private void setIgnoreKeyEvents(boolean ignoreKeyEvents) {
modelRoot.setProperty(Property.IGNORE_KEY_EVENTS, Boolean
.valueOf(ignoreKeyEvents));
}
Outgoing Methods (calls):
jfreerails.client.top.UserInputOnMapController.setup
Javadoc:
No Javadoc available
Method code:
public void setup(MapViewJComponent mv, TrackMoveProducer trackBuilder,
StationTypesPopup stPopup, ModelRoot mr, DialogueBoxController dbc,
FreerailsCursor cursor, BuildTrackController buildTrack, TrainRenderer trainRenderer) {
this.dialogueBoxController = dbc;
this.mapView = mv;
this.stationTypesPopup = stPopup;
this.trackBuilder = trackBuilder;
this.buildTrack = buildTrack;
this.trainRenderer = trainRenderer;
buildIndustryJPopupMenu.setup(mr, null, null);
/*
* We attempt to remove listeners before adding them to prevent them
* being added several times.
*/
mapView.removeMouseListener(mouseInputAdapter);
mapView.addMouseListener(mouseInputAdapter);
mapView.removeMouseMotionListener(mouseInputAdapter);
mapView.addMouseMotionListener(mouseInputAdapter);
mapView.removeKeyListener(this);
mapView.addKeyListener(this);
}
Outgoing Methods (calls):
jfreerails.client.top.UserMessageGenerator.logSpeed
Javadoc:
No Javadoc available
Method code:
public void logSpeed() {
ReadOnlyWorld world = modelRoot.getWorld();
GameSpeed speed = ((GameSpeed) world.get(ITEM.GAME_SPEED));
int gameSpeed = speed.getSpeed();
if (gameSpeed <= 0) {
modelRoot
.setProperty(Property.PERMANENT_MESSAGE, "Game is paused.");
/*
* Also hide any other message. It looks silly if it says "Game is
* paused." and "Game speed: fast" on screen at the same time!
*/
modelRoot.setProperty(Property.QUICK_MESSAGE, "");
} else {
modelRoot.setProperty(Property.PERMANENT_MESSAGE, null);
String gameSpeedDesc = actionRoot.getServerControls()
.getGameSpeedDesc(gameSpeed);
modelRoot.setProperty(Property.QUICK_MESSAGE, "Game speed: "
+ gameSpeedDesc);
}
}
Outgoing Methods (calls):
jfreerails.client.top.UserMessageGenerator.processMove
Javadoc:
No Javadoc available
Method code:
public void processMove(Move move) {
if (move instanceof CompositeMove) {
ImList<Move> moves = ((CompositeMove) move).getMoves();
for (int i = 0; i < moves.size(); i++) {
processMove(moves.get(i));
}
}
if (move instanceof WorldDiffMove) {
WorldDiffMove wdm = (WorldDiffMove) move;
if (wdm.getCause().equals(WorldDiffMove.Cause.TrainArrives)) {
trainArrives(wdm);
}
} else if (move instanceof ChangeGameSpeedMove) {
logSpeed();
}
}
Outgoing Methods (calls):
jfreerails.client.top.UserMessageGenerator.trainArrives
Javadoc:
/** Generates a message giving details of any cargo delivered and plays * a cash register sound to indicate that revenue is coming in. */
Method code:
/** Generates a message giving details of any cargo delivered and plays
* a cash register sound to indicate that revenue is coming in.
*/
private void trainArrives(WorldDiffMove wdm) {
ArrayList<DeliverCargoReceipt> cargoDelivered = new ArrayList<DeliverCargoReceipt>();
CompositeMove listChanges = wdm.getListChanges();
for (int i = 0; i < listChanges.size(); i++) {
Move m = listChanges.getMoves().get(i);
if (m instanceof AddTransactionMove) {
AddTransactionMove atm = (AddTransactionMove) m;
if(!atm.getPrincipal().equals(modelRoot.getPrincipal())){
//We don't want to know about other players' income!
return;
}
Transaction t = atm.getTransaction();
if (t instanceof DeliverCargoReceipt) {
DeliverCargoReceipt receipt = (DeliverCargoReceipt) t;
cargoDelivered.add(receipt);
}
}
}
if (cargoDelivered.size() > 0) {
ReadOnlyWorld world = modelRoot.getWorld();
StringBuffer message = new StringBuffer();
DeliverCargoReceipt first = cargoDelivered.get(0);
int stationId = first.getStationId();
int trainId = first.getTrainId();
message.append("Train #");
message.append(trainId + 1); // So that the first train
// is #1, not #0.
message.append(" arrives at ");
StationModel station = (StationModel) world.get(modelRoot
.getPrincipal(), KEY.STATIONS, stationId);
message.append(station.getStationName());
message.append("\n");
long revenue = 0;
int[] cargoQuantities = new int[modelRoot.getWorld().size(
SKEY.CARGO_TYPES)];
for (DeliverCargoReceipt receipt : cargoDelivered) {
CargoBatch batch = receipt.getCb();
revenue += receipt.deltaCash().getAmount();
cargoQuantities[batch.getCargoType()] = receipt
.getQuantity();
}
for (int i = 0; i < cargoQuantities.length; i++) {
int j = cargoQuantities[i];
if (j > 0) {
CargoType cargoType = (CargoType) world.get(
SKEY.CARGO_TYPES, i);
message.append(j);
message.append(" ");
message.append(cargoType.getDisplayName());
message.append("\n");
}
}
message.append("Revenue $");
message.append(formatter.format(revenue));
modelRoot.setProperty(Property.QUICK_MESSAGE, message
.toString());
// Play the sound of cash coming in. The greater the
// revenue,
// the more loops of the sample we play.
int loops = (int) revenue / 4000;
try {
soundManager.playSound(
"/jfreerails/client/sounds/cash.wav", loops);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Outgoing Methods (calls):
jfreerails.client.view.ActionRoot.getBuildTrainDialogAction
Javadoc:
No Javadoc available
Method code:
public Action getBuildTrainDialogAction() {
return buildTrainDialogAction;
}
No outgoing methods.
jfreerails.client.view.ActionRoot.getDialogueBoxController
Javadoc:
No Javadoc available
Method code:
public DialogueBoxController getDialogueBoxController() {
return dialogueBoxController;
}
No outgoing methods.
jfreerails.client.view.ActionRoot.getServerControls
Javadoc:
No Javadoc available
Method code:
public ServerControlModel getServerControls() {
return serverControls;
}
No outgoing methods.
jfreerails.client.view.ActionRoot.getStationBuildModel
Javadoc:
No Javadoc available
Method code:
public StationBuildModel getStationBuildModel() {
return stationBuildModel;
}
No outgoing methods.
jfreerails.client.view.ActionRoot.getTrackMoveProducer
Javadoc:
No Javadoc available
Method code:
public TrackMoveProducer getTrackMoveProducer() {
return trackMoveProducer;
}
No outgoing methods.
jfreerails.client.view.ActionRoot.setDialogueBoxController
Javadoc:
No Javadoc available
Method code:
public void setDialogueBoxController(
DialogueBoxController dialogueBoxController) {
this.dialogueBoxController = dialogueBoxController;
}
No outgoing methods.
jfreerails.client.view.ActionRoot.setup
Javadoc:
/** * Call this method when a new game is started or a game is loaded. */
Method code:
/**
* Call this method when a new game is started or a game is loaded.
*/
public void setup(ModelRootImpl modelRoot, RenderersRoot vl) {
serverControls.setup(modelRoot, dialogueBoxController);
if (!modelRoot.hasBeenSetup)
throw new IllegalStateException();
ReadOnlyWorld world = modelRoot.getWorld();
if (world.size(SKEY.TRACK_RULES) > 0) {
trackMoveProducer = new TrackMoveProducer(modelRoot);
stationBuildModel = new StationBuildModel(new StationBuilder(
modelRoot), vl, modelRoot);
}
}
Outgoing Methods (calls):
jfreerails.client.view.ActiveView.setup
Javadoc:
No Javadoc available
Method code:
void setup(ModelRoot modelRoot, ActionRoot ar, RenderersRoot vl,
ActionListener submitButtonCallBack);
No outgoing methods.
jfreerails.client.view.BalanceSheetGeneratorTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
world = new WorldImpl(10, 10);
player = new Player("Player X", world.getNumberOfPlayers());
world.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
world.setTime(new GameTime(0));
Move addPlayerMove = AddPlayerMove.generateMove(world, player);
MoveStatus ms = addPlayerMove.doMove(world, player.getPrincipal());
assertTrue(ms.message, ms.ok);
world.setTime(new GameTime(100));
}
Outgoing Methods (calls):
jfreerails.client.view.BalanceSheetGeneratorTest.testBondsFigure
Javadoc:
No Javadoc available
Method code:
public void testBondsFigure() {
BalanceSheetGenerator generator = new BalanceSheetGenerator(world,
player.getPrincipal());
Money expectedBondValue = new Money(BondTransaction.BOND_VALUE_ISSUE
.getAmount());
assertEquals(expectedBondValue.changeSign(), generator.total.loans);
assertEquals(expectedBondValue.changeSign(), generator.ytd.loans);
}
Outgoing Methods (calls):
jfreerails.client.view.BalanceSheetGeneratorTest.testStockHolderEquityFigure
Javadoc:
No Javadoc available
Method code:
public void testStockHolderEquityFigure() {
BalanceSheetGenerator generator = new BalanceSheetGenerator(world,
player.getPrincipal());
Money expectStockHolderEquity = new Money(-500000);
assertEquals(expectStockHolderEquity, generator.total.equity);
}
Outgoing Methods (calls):
jfreerails.client.view.BalanceSheetHtmlJPanel.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(Graphics g) {
/* Check to see if the text needs updating before painting. */
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
int currentNumberOfTransactions = world
.getNumberOfTransactions(playerPrincipal);
if (currentNumberOfTransactions != lastNumTransactions) {
updateHtml();
}
super.paintComponent(g);
}
Outgoing Methods (calls):
jfreerails.client.view.BalanceSheetHtmlJPanel.setup
Javadoc:
No Javadoc available
Method code:
@Override
public void setup(ModelRoot modelRoot, RenderersRoot vl, Action closeAction) {
super.setup(modelRoot, vl, closeAction);
this.modelRoot = modelRoot;
updateHtml();
}
Outgoing Methods (calls):
jfreerails.client.view.BalanceSheetHtmlJPanel.updateHtml
Javadoc:
No Javadoc available
Method code:
private void updateHtml() {
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
BalanceSheetGenerator balanceSheetGenerator = new BalanceSheetGenerator(
world, playerPrincipal);
String populatedTemplate = populateTokens(template,
balanceSheetGenerator);
setHtml(populatedTemplate);
}
Outgoing Methods (calls):
jfreerails.client.view.BrokerJFrame.initComponents
Javadoc:
/** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */
Method code:
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
htmlJLabel = new javax.swing.JLabel();
done = new javax.swing.JButton();
brokerMenu = new javax.swing.JMenuBar();
bonds = new javax.swing.JMenu();
issueBond = new javax.swing.JMenuItem();
repayBond = new javax.swing.JMenuItem();
stocks = new javax.swing.JMenu();
getContentPane().setLayout(new java.awt.GridBagLayout());
jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jPanel1.setLayout(new java.awt.BorderLayout());
htmlJLabel.setFont(new java.awt.Font("Dialog", 0, 12));
htmlJLabel.setText("sdfa");
htmlJLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
htmlJLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
jPanel1.add(htmlJLabel, java.awt.BorderLayout.CENTER);
jScrollPane1.setViewportView(jPanel1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(jScrollPane1, gridBagConstraints);
done.setText("Close");
done.setVerifyInputWhenFocusTarget(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
getContentPane().add(done, gridBagConstraints);
bonds.setText("Bonds");
issueBond.setText("Issue Bond");
bonds.add(issueBond);
repayBond.setText("Repay Bond");
bonds.add(repayBond);
brokerMenu.add(bonds);
stocks.setText("Stocks");
brokerMenu.add(stocks);
setJMenuBar(brokerMenu);
pack();
}
No outgoing methods.
jfreerails.client.view.BrokerJFrame.loadText
Javadoc:
/** Load the help text from file. */
Method code:
/** Load the help text from file. */
String loadText(final URL htmlUrl) {
try {
InputStream in = htmlUrl.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
new DataInputStream(in)));
String line;
String text = "";
while ((line = br.readLine()) != null) {
text = text + line;
}
return text;
} catch (Exception e) {
e.printStackTrace();
logger.warning(htmlUrl.toString());
return "Couldn't read: " + htmlUrl;
}
}
No outgoing methods.
jfreerails.client.view.BrokerJFrame.populateTokens
Javadoc:
No Javadoc available
Method code:
public String populateTokens(String template, Object context) {
StringTokenizer tokenizer = new StringTokenizer(template, "$");
String output = "";
while (tokenizer.hasMoreTokens()) {
output += tokenizer.nextToken();
if (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
String value;
if (context instanceof HashMap) {
value = (String) ((HashMap) context).get(token);
} else {
try {
Field field = context.getClass().getField(token);
value = field.get(context).toString();
} catch (Exception e) {
e.printStackTrace();
throw new NoSuchElementException(token);
}
}
output += value;
}
}
return output;
}
No outgoing methods.
jfreerails.client.view.BrokerJFrame.setHtml
Javadoc:
No Javadoc available
Method code:
void setHtml(String s) {
htmlJLabel.setText(s);
}
No outgoing methods.
jfreerails.client.view.BrokerJFrame.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot m, RenderersRoot vl,
Action closeAction) {
this.done.setAction(closeAction);
}
No outgoing methods.
jfreerails.client.view.BrokerScreenGeneratorTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
// TODO Auto-generated method stub
super.setUp();
world = new WorldImpl(10, 10);
// Set the time..
world.set(ITEM.CALENDAR, new GameCalendar(12000, 1840));
Player p = MapFixtureFactory.TEST_PLAYER;
AddPlayerMove apm = AddPlayerMove.generateMove(world, p);
MoveStatus ms = apm.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.isOk());
playerID = world.getNumberOfPlayers() - 1;
principal = p.getPrincipal();
}
Outgoing Methods (calls):
jfreerails.client.view.BrokerScreenGeneratorTest.testBuyingStock
Javadoc:
/** * Testcase to reproduce bug [ 1341365 ] Exception when calculating stock * price after buying shares */
Method code:
/**
* Testcase to reproduce bug [ 1341365 ] Exception when calculating stock
* price after buying shares
*/
public void testBuyingStock() {
for (int i = 0; i < 9; i++) {
StockPrice stockPrice = new StockPriceCalculator(world).calculate()[playerID];
Money sharePrice = stockPrice.treasuryBuyPrice;
StockTransaction t = StockTransaction.buyOrSellStock(playerID,
StockTransaction.STOCK_BUNDLE_SIZE, sharePrice);
Move move = new AddTransactionMove(principal, t);
MoveStatus ms = move.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.isOk());
//The line below threw an exception that caused bug 1341365.
BrokerScreenGenerator brokerScreenGenerator = new BrokerScreenGenerator(world, principal);
assertNotNull(brokerScreenGenerator);
}
}
Outgoing Methods (calls):
jfreerails.client.view.BrokerScreenHtmlJFrame.enableAndDisableActions
Javadoc:
No Javadoc available
Method code:
private void enableAndDisableActions(){
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal p = modelRoot.getPrincipal();
FinancialDataGatherer thisDataGatherer = new FinancialDataGatherer(
world, p);
StockPrice[] stockPrices = new StockPriceCalculator(world).calculate();
long highestAffordablePrice = world.getCurrentBalance(p).getAmount() / StockTransaction.STOCK_BUNDLE_SIZE;
//Enable and disable stock actions.
for(int playerId = 0; playerId < world.getNumberOfPlayers(); playerId++){
Player temp = modelRoot.getWorld().getPlayer(playerId);
FreerailsPrincipal otherPrincipal = temp.getPrincipal();
FinancialDataGatherer otherDataGatherer = new FinancialDataGatherer(world, otherPrincipal);
//If this RR has stock in other RR, then enable sell stock
boolean hasStockInRR = thisDataGatherer.getStockInRRs()[playerId] > 0;
sellStock[playerId].setEnabled(hasStockInRR);
//If the public own some stock, then enable buy stock.
boolean isStockAvailable = otherDataGatherer.sharesHeldByPublic() > 0;
buyStock[playerId].setEnabled(isStockAvailable);
//Don't let player buy 100% of treasury stock.
if(otherPrincipal.equals(p)){
int treasuryStock = otherDataGatherer.treasuryStock();
int totalStock = otherDataGatherer.totalShares();
if(StockTransaction.STOCK_BUNDLE_SIZE + treasuryStock >= totalStock){
buyStock[playerId].setEnabled(false);
}
}
//Don't let the player buy stock if they cannot afford it.
if(stockPrices[playerId].currentPrice.getAmount() > highestAffordablePrice){
buyStock[playerId].setEnabled(false);
}
}
//Enable and disable bond actions.
int outstandingBonds = thisDataGatherer.getBonds();
repayBondAction.setEnabled(outstandingBonds > 0);
issueBondAction.setEnabled(outstandingBonds < 4);
}
Outgoing Methods (calls):
jfreerails.client.view.BrokerScreenHtmlJFrame.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(Graphics g) {
/* Check to see if the text needs updating before painting. */
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
int currentNumberOfTransactions = world
.getNumberOfTransactions(playerPrincipal);
if (currentNumberOfTransactions != lastNumTransactions) {
updateHtml();
}
super.paintComponent(g);
}
Outgoing Methods (calls):
jfreerails.client.view.BrokerScreenHtmlJFrame.setup
Javadoc:
No Javadoc available
Method code:
@Override
public void setup(final ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
super.setup(modelRoot, vl, closeAction);
financialDataGatherer = new FinancialDataGatherer(modelRoot.getWorld(),
modelRoot.getPrincipal());
this.modelRoot = modelRoot;
setupStockMenu();
updateHtml();
// Sets up the BrokerScreen and Adds ActionListeners to the Menu
issueBond.setAction(issueBondAction);
repayBond.setAction(repayBondAction);
}
Outgoing Methods (calls):
jfreerails.client.view.BrokerScreenHtmlJFrame.setupStockMenu
Javadoc:
No Javadoc available
Method code:
private void setupStockMenu(){
stocks.removeAll();
ReadOnlyWorld world = modelRoot.getWorld();
int thisPlayerId = world.getID(modelRoot.getPrincipal());
int numberOfPlayers = world.getNumberOfPlayers();
buyStock = new Action[numberOfPlayers];
sellStock = new Action[numberOfPlayers];
for(int playerId = 0 ; playerId < numberOfPlayers; playerId++){
final boolean isThisPlayer = playerId == thisPlayerId;
final int otherPlayerId = playerId;
Player otherPlayer = world.getPlayer(playerId);
String playerLabel = isThisPlayer ? "Treasury stock" : otherPlayer.getName();
String buyLabel = "Buy 10,000 shares of " + playerLabel;
String sellLabel = "Sell 10,000 shares of " + playerLabel;
buyStock[playerId] = new AbstractAction(buyLabel) {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
StockPrice stockPrice = new StockPriceCalculator(modelRoot.getWorld()).calculate()[otherPlayerId];
Money sharePrice = isThisPlayer ? stockPrice.treasuryBuyPrice : stockPrice.buyPrice;
StockTransaction t = StockTransaction
.buyOrSellStock(otherPlayerId, StockTransaction.STOCK_BUNDLE_SIZE, sharePrice);
Move move = new AddTransactionMove(modelRoot.getPrincipal(), t);
modelRoot.doMove(move);
updateHtml();
}
};
sellStock[playerId] = new AbstractAction(sellLabel) {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
StockPrice stockPrice = new StockPriceCalculator(modelRoot.getWorld()).calculate()[otherPlayerId];
Money sharePrice = isThisPlayer ? stockPrice.treasurySellPrice : stockPrice.sellPrice;
StockTransaction t = StockTransaction
.buyOrSellStock(otherPlayerId, -StockTransaction.STOCK_BUNDLE_SIZE, sharePrice);
Move move = new AddTransactionMove(modelRoot.getPrincipal(), t);
modelRoot.doMove(move);
updateHtml();
}
};
stocks.add(buyStock[playerId]);
stocks.add(sellStock[playerId]);
}
enableAndDisableActions();
}
Outgoing Methods (calls):
jfreerails.client.view.BrokerScreenHtmlJFrame.updateHtml
Javadoc:
No Javadoc available
Method code:
private void updateHtml() {
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal p = modelRoot.getPrincipal();
brokerScreenGenerator = new BrokerScreenGenerator(world, p);
// this is where the Menu get Enable and Disable by if you own any stock
// or if the TotalShares are 0
StringBuffer populatedTemplate = new StringBuffer();
populatedTemplate.append("<html>");
populatedTemplate
.append(populateTokens(template, brokerScreenGenerator));
for (int i = 0; i < world.getNumberOfPlayers(); i++) {
if (!(world.getPlayer(i).getPrincipal().equals(p))) {
BrokerScreenGenerator temp = new BrokerScreenGenerator(world,
world.getPlayer(i).getPrincipal());
populatedTemplate.append(populateTokens(template, temp));
}
}
populatedTemplate.append("</html>");
String html = populatedTemplate.toString();
setHtml(html);
enableAndDisableActions();
}
Outgoing Methods (calls):
jfreerails.client.view.BuildTrackJPanel.addNoBridgesButton
Javadoc:
No Javadoc available
Method code:
private void addNoBridgesButton() {
JToggleButton toggleButton = new JToggleButton();
bridgeButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon("no_bridges"));
toggleButton.setPreferredSize(new java.awt.Dimension(36, 36));
toggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectionSet.put(TrackRule.TrackCategories.bridge, null);
setBuildTrackStrategy();
}
});
toggleButton.setToolTipText("Don't build bridges");
bridgesJPanel.add(toggleButton);
}
Outgoing Methods (calls):
jfreerails.client.view.BuildTrackJPanel.addNoTunnelsButton
Javadoc:
No Javadoc available
Method code:
private void addNoTunnelsButton() {
JToggleButton toggleButton = new JToggleButton();
tunnelButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon("no_tunnels"));
toggleButton.setPreferredSize(new java.awt.Dimension(36, 36));
toggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectionSet.put(TrackRule.TrackCategories.tunnel, null);
setBuildTrackStrategy();
}
});
toggleButton.setToolTipText("Don't build tunnels");
tunnelsJPanel.add(toggleButton);
}
Outgoing Methods (calls):
jfreerails.client.view.BuildTrackJPanel.addStationActionPerformed
Javadoc:
No Javadoc available
Method code:
private void addStationActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addStationActionPerformed
setVisible(false, false, false, true);
setTrackBuilderMode(BUILD_STATION);
}// GEN-LAST:event_addStationActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.BuildTrackJPanel.addTrackActionPerformed
Javadoc:
/** * Handles the action event triggered when the "Add Track" button is clicked. * This method updates the UI visibility settings, cancels any ongoing station placement, * and switches the track builder mode to {@code BUILD_TRACK}. * * @param evt The {@code ActionEvent} triggered by the user's interaction with the "Add Track" button. */
Method code:
private void addTrackActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addTrackActionPerformed
setVisible(true, true, true, false);
cancelStationPlacement();
setTrackBuilderMode(BUILD_TRACK);
}// GEN-LAST:event_addTrackActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.BuildTrackJPanel.bulldozeActionPerformed
Javadoc:
No Javadoc available
Method code:
private void bulldozeActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bulldozeActionPerformed
setVisible(false, false, false, false);
cancelStationPlacement();
setTrackBuilderMode(REMOVE_TRACK);
}// GEN-LAST:event_bulldozeActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.BuildTrackJPanel.cancelStationPlacement
Javadoc:
No Javadoc available
Method code:
private void cancelStationPlacement() {
// Cancel build station mode..
stationBuildModel.getStationCancelAction().actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
}
Outgoing Methods (calls):
jfreerails.client.view.BuildTrackJPanel.formKeyPressed
Javadoc:
No Javadoc available
Method code:
private void formKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_formKeyPressed
viewMode.doClick();
}// GEN-LAST:event_formKeyPressed
No outgoing methods.
jfreerails.client.view.BuildTrackJPanel.formKeyTyped
Javadoc:
/** * Handles the key typed event by invoking the doClick method on the viewMode. * This method is triggered when a key is typed in the associated component, * causing the view mode to perform its default click action. * * @param evt the KeyEvent object representing the key typed event */
Method code:
private void formKeyTyped(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_formKeyTyped
viewMode.doClick();
}// GEN-LAST:event_formKeyTyped
No outgoing methods.
jfreerails.client.view.BuildTrackJPanel.getIcon
Javadoc:
No Javadoc available
Method code:
private ImageIcon getIcon(String typeName) {
try {
String relativeFileName = "icons" + File.separator + typeName
+ ".png";
relativeFileName = relativeFileName.replace(' ', '_');
Image im = imageManager.getImage(relativeFileName);
return new ImageIcon(im);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException(e);
}
}
Outgoing Methods (calls):
jfreerails.client.view.BuildTrackJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
buildModeButtonGroup = new javax.swing.ButtonGroup();
trackButtonGroup = new javax.swing.ButtonGroup();
bridgeButtonGroup = new javax.swing.ButtonGroup();
stationButtonGroup = new javax.swing.ButtonGroup();
tunnelButtonGroup = new javax.swing.ButtonGroup();
buildModeJPanel = new javax.swing.JPanel();
addTrack = new javax.swing.JToggleButton();
upgradeTrack = new javax.swing.JToggleButton();
addStation = new javax.swing.JToggleButton();
bulldoze = new javax.swing.JToggleButton();
viewMode = new javax.swing.JToggleButton();
trackJPanel = new javax.swing.JPanel();
viewMode1 = new javax.swing.JToggleButton();
bridgesJPanel = new javax.swing.JPanel();
viewMode2 = new javax.swing.JToggleButton();
tunnelsJPanel = new javax.swing.JPanel();
viewMode3 = new javax.swing.JToggleButton();
stationsJPanel = new javax.swing.JPanel();
viewMode4 = new javax.swing.JToggleButton();
spacer = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
setFocusable(false);
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
@Override
public void keyTyped(java.awt.event.KeyEvent evt) {
formKeyTyped(evt);
}
});
buildModeJPanel.setLayout(new java.awt.FlowLayout(
java.awt.FlowLayout.LEFT, 4, 2));
buildModeButtonGroup.add(addTrack);
addTrack.setIcon(getIcon("build track"));
addTrack.setSelected(true);
addTrack.setToolTipText("Build Track");
addTrack.setFocusable(false);
addTrack.setPreferredSize(new java.awt.Dimension(36, 36));
addTrack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addTrackActionPerformed(evt);
}
});
buildModeJPanel.add(addTrack);
buildModeButtonGroup.add(upgradeTrack);
upgradeTrack.setIcon(getIcon("upgrade track"));
upgradeTrack.setToolTipText("Upgrade Track");
upgradeTrack.setFocusable(false);
upgradeTrack.setPreferredSize(new java.awt.Dimension(36, 36));
upgradeTrack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
upgradeTrackActionPerformed(evt);
}
});
buildModeJPanel.add(upgradeTrack);
buildModeButtonGroup.add(addStation);
addStation.setIcon(getIcon("build stations"));
addStation.setToolTipText("Build Station");
addStation.setFocusable(false);
addStation.setPreferredSize(new java.awt.Dimension(36, 36));
addStation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addStationActionPerformed(evt);
}
});
buildModeJPanel.add(addStation);
buildModeButtonGroup.add(bulldoze);
bulldoze.setIcon(getIcon("bulldozer"));
bulldoze.setToolTipText("Remove Track");
bulldoze.setFocusable(false);
bulldoze.setPreferredSize(new java.awt.Dimension(36, 36));
bulldoze.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bulldozeActionPerformed(evt);
}
});
buildModeJPanel.add(bulldoze);
buildModeButtonGroup.add(viewMode);
viewMode.setIcon(getIcon("eye"));
viewMode.setToolTipText("Don't build anything");
viewMode.setFocusable(false);
viewMode.setPreferredSize(new java.awt.Dimension(36, 36));
viewMode.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewModeActionPerformed(evt);
}
});
buildModeJPanel.add(viewMode);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(buildModeJPanel, gridBagConstraints);
trackJPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT,
4, 2));
buildModeButtonGroup.add(viewMode1);
viewMode1.setIcon(getIcon("turn_off"));
viewMode1.setPreferredSize(new java.awt.Dimension(36, 36));
trackJPanel.add(viewMode1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(trackJPanel, gridBagConstraints);
bridgesJPanel.setLayout(new java.awt.FlowLayout(
java.awt.FlowLayout.LEFT, 4, 2));
buildModeButtonGroup.add(viewMode2);
viewMode2.setIcon(getIcon("turn_off"));
viewMode2.setPreferredSize(new java.awt.Dimension(36, 36));
bridgesJPanel.add(viewMode2);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(bridgesJPanel, gridBagConstraints);
tunnelsJPanel.setLayout(new java.awt.FlowLayout(
java.awt.FlowLayout.LEFT, 4, 2));
buildModeButtonGroup.add(viewMode3);
viewMode3.setIcon(getIcon("turn_off"));
viewMode3.setPreferredSize(new java.awt.Dimension(36, 36));
tunnelsJPanel.add(viewMode3);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(tunnelsJPanel, gridBagConstraints);
stationsJPanel.setLayout(new java.awt.FlowLayout(
java.awt.FlowLayout.LEFT, 4, 2));
buildModeButtonGroup.add(viewMode4);
viewMode4.setIcon(getIcon("turn_off"));
viewMode4.setPreferredSize(new java.awt.Dimension(36, 36));
stationsJPanel.add(viewMode4);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(stationsJPanel, gridBagConstraints);
spacer.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 0,
0));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(spacer, gridBagConstraints);
}// GEN-END:initComponents
Outgoing Methods (calls):
jfreerails.client.view.BuildTrackJPanel.setBuildTrackStrategy
Javadoc:
No Javadoc available
Method code:
private void setBuildTrackStrategy() {
ArrayList<Integer> ruleIDs = new ArrayList<Integer>();
ruleIDs.add(selectionSet.get(TrackRule.TrackCategories.track));
ruleIDs.add(selectionSet.get(TrackRule.TrackCategories.bridge));
ruleIDs.add(selectionSet.get(TrackRule.TrackCategories.tunnel));
BuildTrackStrategy bts = BuildTrackStrategy.getMultipleRuleInstance(
ruleIDs, modelRoot.getWorld());
modelRoot.setProperty(ModelRoot.Property.BUILD_TRACK_STRATEGY, bts);
}
Outgoing Methods (calls):
jfreerails.client.view.BuildTrackJPanel.setFocusableFalse
Javadoc:
/** Calls setFocusable(false) for each button in the button group. */
Method code:
/** Calls setFocusable(false) for each button in the button group. */
private void setFocusableFalse(ButtonGroup bg) {
for (Enumeration<AbstractButton> buttons = bg.getElements(); buttons
.hasMoreElements();) {
buttons.nextElement().setFocusable(false);
}
}
No outgoing methods.
jfreerails.client.view.BuildTrackJPanel.setTrackBuilderMode
Javadoc:
No Javadoc available
Method code:
private void setTrackBuilderMode(TrackMoveProducer.BuildMode mode) {
trackMoveProducer.setTrackBuilderMode(mode);
modelRoot.setProperty(ModelRoot.Property.TRACK_BUILDER_MODE, mode);
}
Outgoing Methods (calls):
jfreerails.client.view.BuildTrackJPanel.setVisible
Javadoc:
No Javadoc available
Method code:
private void setVisible(boolean track, boolean bridges, boolean tunnels,
boolean stations) {
trackJPanel.setVisible(bridges);
bridgesJPanel.setVisible(bridges);
tunnelsJPanel.setVisible(tunnels);
stationsJPanel.setVisible(stations);
}
No outgoing methods.
jfreerails.client.view.BuildTrackJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot mr, ActionRoot ar, RenderersRoot vl,
ActionListener al) {
modelRoot = mr;
stationBuildModel = ar.getStationBuildModel();
trackMoveProducer = ar.getTrackMoveProducer();
if (null == trackMoveProducer)
throw new NullPointerException();
selectionSet = new HashMap<TrackRule.TrackCategories, Integer>();
trackButtonGroup = new javax.swing.ButtonGroup();
bridgeButtonGroup = new javax.swing.ButtonGroup();
stationButtonGroup = new javax.swing.ButtonGroup();
tunnelButtonGroup = new javax.swing.ButtonGroup();
// Remove any existing buttons.
bridgesJPanel.removeAll();
stationsJPanel.removeAll();
trackJPanel.removeAll();
tunnelsJPanel.removeAll();
// Add the new set of buttons.
ReadOnlyWorld world = mr.getWorld();
for (int i = 0; i < world.size(SKEY.TRACK_RULES); i++) {
JToggleButton toggleButton = new JToggleButton();
final Integer ruleID = new Integer(i);
TrackRule rule = (TrackRule) world.get(SKEY.TRACK_RULES, i);
TrackRule.TrackCategories category = rule.getCategory();
Money price = null;
switch (category) {
case track:
trackButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon(rule.getTypeName()));
toggleButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
selectionSet
.put(TrackRule.TrackCategories.track,
ruleID);
setBuildTrackStrategy();
}
});
price = rule.getPrice();
trackJPanel.add(toggleButton);
break;
case bridge:
bridgeButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon(rule.getTypeName()));
toggleButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
selectionSet.put(
TrackRule.TrackCategories.bridge,
ruleID);
setBuildTrackStrategy();
}
});
bridgesJPanel.add(toggleButton);
price = rule.getFixedCost();
break;
case tunnel:
tunnelButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon(rule.getTypeName()));
toggleButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
selectionSet.put(
TrackRule.TrackCategories.tunnel,
ruleID);
setBuildTrackStrategy();
}
});
price = rule.getPrice();
tunnelsJPanel.add(toggleButton);
break;
case station:
stationButtonGroup.add(toggleButton);
toggleButton.setAction(stationBuildModel
.getStationChooseAction(ruleID));
toggleButton.setIcon(getIcon(rule.getTypeName()));
toggleButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
selectionSet.put(
TrackRule.TrackCategories.station,
ruleID);
}
});
stationsJPanel.add(toggleButton);
price = rule.getFixedCost();
break;
}
toggleButton.setPreferredSize(new java.awt.Dimension(36, 36));
String tooltip = Utils.capitalizeEveryWord(rule.getTypeName())
+ " $" + price.toString();
toggleButton.setToolTipText(tooltip);
if (!selectionSet.containsKey(category)) {
selectionSet.put(category, new Integer(i));
toggleButton.setSelected(true);
}
}
addNoTunnelsButton();
addNoBridgesButton();
// Default to add track.
addTrackActionPerformed(null);
buildModeButtonGroup.setSelected(addTrack.getModel(), true);
setBuildTrackStrategy();
// Make the buttons non-focusable
setFocusableFalse(bridgeButtonGroup);
setFocusableFalse(trackButtonGroup);
setFocusableFalse(tunnelButtonGroup);
setFocusableFalse(stationButtonGroup);
setFocusableFalse(buildModeButtonGroup);
// Add button click
// buildTrackJPanel.addKeyListener(new KeyListener(){
// public void keyPressed(KeyEvent e){
// System.out.println(e.getKeyCode());
// viewMode.doClick();
// }
// public void keyReleased(KeyEvent e){
//
// }
// public void keyTyped(KeyEvent e){
//
// }
// });
}
Outgoing Methods (calls):
jfreerails.client.view.BuildTrackJPanel.upgradeTrackActionPerformed
Javadoc:
No Javadoc available
Method code:
private void upgradeTrackActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_upgradeTrackActionPerformed
setVisible(true, true, false, false);
cancelStationPlacement();
setTrackBuilderMode(UPGRADE_TRACK);
}// GEN-LAST:event_upgradeTrackActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.BuildTrackJPanel.viewModeActionPerformed
Javadoc:
No Javadoc available
Method code:
private void viewModeActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_viewModeActionPerformed
setVisible(false, false, false, false);
cancelStationPlacement();
setTrackBuilderMode(IGNORE_TRACK);
}// GEN-LAST:event_viewModeActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.BuildTrainDialogAction.actionPerformed
Javadoc:
No Javadoc available
Method code:
public void actionPerformed(ActionEvent e) {
if (dialogueBoxController != null) {
dialogueBoxController.showSelectEngine();
}
}
Outgoing Methods (calls):
jfreerails.client.view.CargoWaitingAndDemandedJPanel.display
Javadoc:
No Javadoc available
Method code:
public void display(int newStationID) {
StationModel station = (StationModel) world.get(principal,
KEY.STATIONS, newStationID);
this.stationName.setText(station.getStationName());
final ImmutableCargoBundle cargoWaiting = (ImmutableCargoBundle) world
.get(principal, KEY.CARGO_BUNDLES, station.getCargoBundleID());
// count the number of cargo types waiting and demanded.
final ArrayList<String> typeWaiting = new ArrayList<String>();
final ArrayList<Integer> quantityWaiting = new ArrayList<Integer>();
final Vector<String> typeDemanded = new Vector<String>();
for (int i = 0; i < world.size(SKEY.CARGO_TYPES); i++) {
CargoType cargoType = (CargoType) world.get(SKEY.CARGO_TYPES, i);
int amountWaiting = cargoWaiting.getAmount(i);
if (0 != amountWaiting) {
typeWaiting.add(cargoType.getDisplayName());
int carloads = amountWaiting
/ WagonType.UNITS_OF_CARGO_PER_WAGON;
quantityWaiting.add(new Integer(carloads));
}
if (station.getDemand().isCargoDemanded(i)) {
typeDemanded.add(cargoType.getDisplayName());
}
}
/*
* The table shows the cargo waiting at the station. First column is
* cargo type; second column is quantity in carloads.
*/
TableModel tableModel = new AbstractTableModel() {
private static final long serialVersionUID = 3760559784860071476L;
public int getRowCount() {
return typeWaiting.size();
}
public int getColumnCount() {
return 2;
}
public Object getValueAt(int row, int column) {
if (0 == column) {
return typeWaiting.get(row);
}
return quantityWaiting.get(row);
}
};
this.waitingJTable.setModel(tableModel);
/* The list shows the cargo demanded by the station. */
this.demandsJList.setListData(typeDemanded);
this.invalidate();
}
Outgoing Methods (calls):
jfreerails.client.view.CargoWaitingAndDemandedJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
stationName = new javax.swing.JLabel();
waiting = new javax.swing.JLabel();
waitingJTable = new javax.swing.JTable();
demands = new javax.swing.JLabel();
demandsJList = new javax.swing.JList();
spacer = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(100, 200));
jScrollPane1.setBorder(null);
jScrollPane1
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jPanel1.setLayout(new java.awt.GridBagLayout());
stationName.setText("Station Name");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
jPanel1.add(stationName, gridBagConstraints);
waiting.setText("Waiting");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
jPanel1.add(waiting, gridBagConstraints);
waitingJTable.setBackground(javax.swing.UIManager.getDefaults()
.getColor("Button.background"));
waitingJTable.setFont(new java.awt.Font("Dialog", 0, 10));
waitingJTable.setModel(new javax.swing.table.DefaultTableModel(
new Object[][] { { "Mail", "4" }, { "Passengers", null } },
new String[] { "Title 1", "Title 2" }));
waitingJTable
.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
waitingJTable.setFocusable(false);
waitingJTable.setRequestFocusEnabled(false);
waitingJTable.setRowSelectionAllowed(false);
waitingJTable.setShowHorizontalLines(false);
waitingJTable.setShowVerticalLines(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
jPanel1.add(waitingJTable, gridBagConstraints);
demands.setText("Demands");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel1.add(demands, gridBagConstraints);
demandsJList.setBackground(javax.swing.UIManager.getDefaults()
.getColor("Button.background"));
demandsJList.setFont(new java.awt.Font("Dialog", 0, 10));
demandsJList.setFocusable(false);
demandsJList.setRequestFocusEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
jPanel1.add(demandsJList, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel1.add(spacer, gridBagConstraints);
jScrollPane1.setViewportView(jPanel1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}// GEN-END:initComponents
No outgoing methods.
jfreerails.client.view.CargoWaitingAndDemandedJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot model, RenderersRoot vl,
Action closeAction) {
this.world = model.getWorld();
this.principal = model.getPrincipal();
}
Outgoing Methods (calls):
jfreerails.client.view.CashJLabel.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(Graphics g) {
if (null != w) {
Money m = w.getCurrentBalance(principal);
String s = m.toString();
this.setText("$" + s);
}
super.paintComponent(g);
}
Outgoing Methods (calls):
jfreerails.client.view.CashJLabel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot model, RenderersRoot vl,
Action closeAction) {
this.w = model.getWorld();
principal = model.getPrincipal();
}
Outgoing Methods (calls):
jfreerails.client.view.ConfirmExitJPanel.confirmExitActionPerformed
Javadoc:
No Javadoc available
Method code:
private void confirmExitActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_confirmExitActionPerformed
System.exit(0);
}// GEN-LAST:event_confirmExitActionPerformed
No outgoing methods.
jfreerails.client.view.ConfirmExitJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
confirmExit = new javax.swing.JButton();
closeJButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(240, 140));
jLabel1.setText("Are you sure you want to Exit?");
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
jPanel1.add(jLabel1);
add(jPanel1, new java.awt.GridBagConstraints());
jPanel2.setLayout(new java.awt.GridBagLayout());
confirmExit.setText("Exit");
confirmExit.setContentAreaFilled(false);
confirmExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
confirmExitActionPerformed(evt);
}
});
jPanel2.add(confirmExit, new java.awt.GridBagConstraints());
closeJButton.setText("Cancel");
jPanel2.add(closeJButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.ipadx = 15;
gridBagConstraints.insets = new java.awt.Insets(3, 0, 0, 0);
add(jPanel2, gridBagConstraints);
}// GEN-END:initComponents
Outgoing Methods (calls):
jfreerails.client.view.ConfirmExitJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
closeJButton.setAction(closeAction);
}
No outgoing methods.
jfreerails.client.view.DateJLabel.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(Graphics g) {
if (null != w) {
GameTime time = w.currentTime();
GameCalendar gameCalendar = (GameCalendar) w.get(ITEM.CALENDAR);
String s = gameCalendar.getYearAndMonth(time.getTicks());
super.setText(s);
}
super.paintComponent(g);
}
Outgoing Methods (calls):
jfreerails.client.view.DateJLabel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot model, RenderersRoot vl,
Action closeAction) {
this.w = model.getWorld();
}
Outgoing Methods (calls):
jfreerails.client.view.DetailMapRenderer.getBuildTrackController
Javadoc:
No Javadoc available
Method code:
public BuildTrackController getBuildTrackController() {
return buildTrackController;
}
No outgoing methods.
jfreerails.client.view.DetailMapRenderer.getMapSizeInPixels
Javadoc:
No Javadoc available
Method code:
public Dimension getMapSizeInPixels() {
return mapSizeInPixels;
}
No outgoing methods.
jfreerails.client.view.DetailMapRenderer.getScale
Javadoc:
No Javadoc available
Method code:
public float getScale() {
return Constants.TILE_SIZE;
}
No outgoing methods.
jfreerails.client.view.DetailMapRenderer.getStationRadius
Javadoc:
No Javadoc available
Method code:
public StationRadiusRenderer getStationRadius() {
return stationRadius;
}
No outgoing methods.
jfreerails.client.view.DetailMapRenderer.getTrainRenderer
Javadoc:
No Javadoc available
Method code:
public TrainRenderer getTrainRenderer() {
return this.trainsview.getTrainRenderer();
}
Outgoing Methods (calls):
jfreerails.client.view.DetailMapRenderer.paintRect
Javadoc:
No Javadoc available
Method code:
public void paintRect(Graphics g, Rectangle visibleRect) {
background.paintRect(g, visibleRect);
trainsview.paint((Graphics2D) g);
stationRadius.paint((Graphics2D) g);
stationBoxes.paint((Graphics2D) g);
buildTrackRenderer.paint((Graphics2D) g);
}
Outgoing Methods (calls):
jfreerails.client.view.DetailMapRenderer.paintTile
Javadoc:
No Javadoc available
Method code:
public void paintTile(Graphics g, int tileX, int tileY) {
background.paintTile(g, tileX, tileY);
trainsview.paint((Graphics2D) g);
stationRadius.paint((Graphics2D) g);
stationBoxes.paint((Graphics2D) g);
buildTrackRenderer.paint((Graphics2D) g);
}
Outgoing Methods (calls):
jfreerails.client.view.DetailMapRenderer.refreshAll
Javadoc:
No Javadoc available
Method code:
public void refreshAll() {
background.refreshAll();
}
Outgoing Methods (calls):
jfreerails.client.view.DetailMapRenderer.refreshTile
Javadoc:
No Javadoc available
Method code:
public void refreshTile(int x, int y) {
background.refreshTile(x, y);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.closeContent
Javadoc:
No Javadoc available
Method code:
public void closeContent() {
if (null != dialogueJInternalFrame) {
dialogueJInternalFrame.setVisible(false);
frame.getLayeredPane().remove(dialogueJInternalFrame);
dialogueJInternalFrame.dispose();
}
if (null != defaultFocusOwner) {
defaultFocusOwner.requestFocus();
}
}
No outgoing methods.
jfreerails.client.view.DialogueBoxController.itemAdded
Javadoc:
No Javadoc available
Method code:
public void itemAdded(KEY key, int index, FreerailsPrincipal principal) {
/*
* Fix for: 910138 After building a train display train orders 910143
* After building station show supply and demand
*/
boolean rightPrincipal = principal
.equals(this.modelRoot.getPrincipal());
if (KEY.TRAINS == key && rightPrincipal) {
this.showTrainOrders(index);
} else if (KEY.STATIONS == key && rightPrincipal) {
this.showStationInfo(index);
}
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.itemRemoved
Javadoc:
No Javadoc available
Method code:
public void itemRemoved(KEY key, int index, FreerailsPrincipal principal) {
// do nothing
}
No outgoing methods.
jfreerails.client.view.DialogueBoxController.listUpdated
Javadoc:
No Javadoc available
Method code:
public void listUpdated(KEY key, int index, FreerailsPrincipal principal) {
// do nothing
}
No outgoing methods.
jfreerails.client.view.DialogueBoxController.setDefaultFocusOwner
Javadoc:
No Javadoc available
Method code:
public void setDefaultFocusOwner(Component defaultFocusOwner) {
this.defaultFocusOwner = defaultFocusOwner;
}
No outgoing methods.
jfreerails.client.view.DialogueBoxController.setup
Javadoc:
/** * Called when a new game is started or a game is loaded. * <p> * <b>Be extremely careful with the references of objects allocated in this * method to avoid memory leaks - see bug 967677 (OutOfMemoryError after * starting several new games). </b> * </p> */
Method code:
/**
* Called when a new game is started or a game is loaded.
* <p>
* <b>Be extremely careful with the references of objects allocated in this
* method to avoid memory leaks - see bug 967677 (OutOfMemoryError after
* starting several new games). </b>
* </p>
*/
public void setup(ModelRootImpl mr, RenderersRoot vl) {
this.modelRoot = mr;
this.vl = vl;
modelRoot.addListListener(this); // When a new train gets built, we
// show the train info etc
this.world = modelRoot.getWorld();
if (world == null)
throw new NullPointerException();
if (vl == null)
throw new NullPointerException();
// Setup the various dialogue boxes.
// setup the terrain info dialogue.
terrainInfo.setup(world, vl);
// setup the supply and demand at station dialogue.
stationInfo.setup(modelRoot, vl, this.closeCurrentDialogue);
modelRoot.addListListener(stationInfo);
// setup the 'show controls' dialogue
showControls.setup(this.modelRoot, vl, this.closeCurrentDialogue);
about.setup(this.modelRoot, vl, this.closeCurrentDialogue);
how2play.setup(this.modelRoot, vl, this.closeCurrentDialogue);
javaProperties.setup(this.modelRoot, vl, this.closeCurrentDialogue);
// Set up train orders dialogue
// trainScheduleJPanel = new TrainScheduleJPanel();
// trainScheduleJPanel.setup(w, vl);
// moveChainFork.add(trainScheduleJPanel);
// Set up select engine dialogue.
selectEngine.setCancelButtonActionListener(this.closeCurrentDialogue);
selectEngine.setup(modelRoot, vl, selectEngineAction);
newspaper.setup(modelRoot, vl, closeCurrentDialogue);
selectWagons.setup(modelRoot, vl, selectWagonsAction);
trainDialogueJPanel.setup(modelRoot, vl, this.closeCurrentDialogue);
modelRoot.addListListener(trainDialogueJPanel);
trainDialogueJPanel
.setTrainDetailsButtonActionListener(trainDetailsButtonActionListener);
trainDialogueJPanel
.setCancelButtonActionListener(this.closeCurrentDialogue);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showAbout
Javadoc:
No Javadoc available
Method code:
public void showAbout() {
showContent(this.about);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showBalanceSheet
Javadoc:
/** * Displays the balance sheet by creating and configuring a BalanceSheetHtmlJPanel, * then showing the content within the dialogue box. */
Method code:
public void showBalanceSheet() {
BalanceSheetHtmlJPanel bs = new BalanceSheetHtmlJPanel();
bs.setup(this.modelRoot, vl, this.closeCurrentDialogue);
this.showContent(bs);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showBrokerScreen
Javadoc:
No Javadoc available
Method code:
public void showBrokerScreen() {
// this is Creating a BrokerScreen Internal Frame in the Main Frame
BrokerScreenHtmlJFrame brokerScreenHtmlJFrame = new BrokerScreenHtmlJFrame();
brokerScreenHtmlJFrame.setup(this.modelRoot, vl,
this.closeCurrentDialogue);
brokerScreenHtmlJFrame.setFrameIcon(null);
showContent(brokerScreenHtmlJFrame);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showContent
Javadoc:
No Javadoc available
Method code:
public void showContent(JComponent component) {
closeContent();
JComponent contentPanel;
if (component instanceof JInternalFrame) {
dialogueJInternalFrame = (JInternalFrame) component;
} else {
if (!(component instanceof View)) {
contentPanel = new javax.swing.JPanel();
contentPanel.setLayout(new java.awt.GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.insets = new Insets(7, 7, 7, 7);
contentPanel.add(component, constraints);
constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 1;
constraints.insets = new Insets(7, 7, 7, 7);
contentPanel.add(closeButton, constraints);
} else {
contentPanel = component;
}
dialogueJInternalFrame = new JInternalFrame();
dialogueJInternalFrame.setFrameIcon(null);
dialogueJInternalFrame.getContentPane().add(contentPanel);
dialogueJInternalFrame.pack();
}
/*
* Make sure the size of the dialogue does not exceed the size of the
* frames content pane.
*/
int parentWidth = frame.getContentPane().getWidth();
int parentHeight = frame.getContentPane().getHeight();
Dimension size = dialogueJInternalFrame.getSize();
if (size.width > parentWidth) {
size.width = parentWidth;
}
if (size.height > parentHeight) {
size.height = parentHeight;
}
dialogueJInternalFrame.setSize(size);
dialogueJInternalFrame.setLocation(
(frame.getWidth() - dialogueJInternalFrame.getWidth()) / 2,
(frame.getHeight() - dialogueJInternalFrame.getHeight()) / 2);
frame.getLayeredPane().add(dialogueJInternalFrame,
JLayeredPane.MODAL_LAYER);
dialogueJInternalFrame.setVisible(true);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showExitDialog
Javadoc:
No Javadoc available
Method code:
// Shows the Exit Dialog -- @author SonnyZ
public void showExitDialog() {
ConfirmExitJPanel bs = new ConfirmExitJPanel();
bs.setup(this.modelRoot, vl, this.closeCurrentDialogue);
this.showContent(bs);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showGameControls
Javadoc:
No Javadoc available
Method code:
public void showGameControls() {
showContent(this.showControls);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showHow2Play
Javadoc:
No Javadoc available
Method code:
public void showHow2Play() {
showContent(this.how2play);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showIncomeStatement
Javadoc:
No Javadoc available
Method code:
public void showIncomeStatement() {
IncomeStatementHtmlJPanel bs = new IncomeStatementHtmlJPanel();
bs.setup(this.modelRoot, vl, this.closeCurrentDialogue);
this.showContent(bs);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showJavaProperties
Javadoc:
No Javadoc available
Method code:
public void showJavaProperties() {
showContent(javaProperties);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showLeaderBoard
Javadoc:
No Javadoc available
Method code:
public void showLeaderBoard() {
LeaderBoardJPanel leaderBoardJPanel = new LeaderBoardJPanel();
leaderBoardJPanel.setup(modelRoot, vl, closeCurrentDialogue);
showContent(leaderBoardJPanel);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showNetworthGraph
Javadoc:
No Javadoc available
Method code:
public void showNetworthGraph() {
final NetWorthGraphJPanel worthGraph = new NetWorthGraphJPanel();
worthGraph.setup(modelRoot, vl, closeCurrentDialogue);
showContent(worthGraph);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showReportBug
Javadoc:
No Javadoc available
Method code:
public void showReportBug(){
CopyableTextJPanel ct = new CopyableTextJPanel();
ct.setText(ReportBugTextGenerator.genText());
showContent(ct);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showSaveGame
Javadoc:
No Javadoc available
Method code:
public void showSaveGame(){
SaveGameJPanel saveGameJPanel = new SaveGameJPanel();
saveGameJPanel.setup(modelRoot, vl, this.closeCurrentDialogue);
showContent(saveGameJPanel);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showSelectEngine
Javadoc:
No Javadoc available
Method code:
public void showSelectEngine() {
WorldIterator wi = new NonNullElements(KEY.STATIONS, world, modelRoot
.getPrincipal());
if (!wi.next()) {
modelRoot.setProperty(Property.QUICK_MESSAGE, "Can't"
+ " build train since there are no stations");
} else {
showContent(selectEngine);
}
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showSelectSavedGame2Load
Javadoc:
No Javadoc available
Method code:
public void showSelectSavedGame2Load(){
Message2Server refreshGames = new RefreshListOfGamesMessage2Server(2);
modelRoot.sendCommand(refreshGames);
LoadGameJPanel loadGameJPane = new LoadGameJPanel();
loadGameJPane.setup(modelRoot, vl, this.closeCurrentDialogue);
showContent(loadGameJPane);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showSelectWagons
Javadoc:
No Javadoc available
Method code:
public void showSelectWagons() {
selectWagons.resetSelectedWagons();
selectWagons.setEngineType(selectEngine.getEngineType());
showContent(selectWagons);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showStationInfo
Javadoc:
No Javadoc available
Method code:
public void showStationInfo(int stationNumber) {
try {
stationInfo.setStation(stationNumber);
showContent(stationInfo);
} catch (NoSuchElementException e) {
logger.warning("Station " + stationNumber + " does not exist!");
}
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showStationOrTerrainInfo
Javadoc:
No Javadoc available
Method code:
public void showStationOrTerrainInfo(int x, int y) {
FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
TrackRule trackRule = tile.getTrackPiece().getTrackRule();
FreerailsPrincipal principal = modelRoot.getPrincipal();
if (trackRule.isStation()
&& tile.getTrackPiece().getOwnerID() == world.getID(principal)) {
for (int i = 0; i < world.size(principal, KEY.STATIONS); i++) {
StationModel station = (StationModel) world.get(principal,
KEY.STATIONS, i);
if (null != station && station.x == x && station.y == y) {
this.showStationInfo(i);
return;
}
}
throw new IllegalStateException("Couldn't find station at " + x
+ ", " + y);
}
this.showTerrainInfo(x, y);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showTerrainInfo
Javadoc:
No Javadoc available
Method code:
public void showTerrainInfo(int x, int y) {
FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
int terrainType = tile.getTerrainTypeID();
showTerrainInfo(terrainType);
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showTrainList
Javadoc:
No Javadoc available
Method code:
public void showTrainList() {
if (world.size(modelRoot.getPrincipal(), KEY.TRAINS) > 0) {
final TrainListJPanel trainList = new TrainListJPanel();
trainList.setup(modelRoot, vl, closeCurrentDialogue);
trainList.setShowTrainDetailsActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int id = trainList.getSelectedTrainID();
showTrainOrders(id);
}
});
showContent(trainList);
} else {
modelRoot.setProperty(Property.QUICK_MESSAGE, "There are"
+ " no trains to display!");
}
}
Outgoing Methods (calls):
jfreerails.client.view.DialogueBoxController.showTrainOrders
Javadoc:
No Javadoc available
Method code:
public void showTrainOrders(int trainId) {
closeContent();
if (trainId != -1) {
trainDialogueJPanel.display(trainId);
showContent(trainDialogueJPanel);
}
}
Outgoing Methods (calls):
jfreerails.client.view.DisplayModesComboBoxModels.addListDataListener
Javadoc:
No Javadoc available
Method code:
public void addListDataListener(javax.swing.event.ListDataListener l) {
}
No outgoing methods.
jfreerails.client.view.DisplayModesComboBoxModels.getElementAt
Javadoc:
No Javadoc available
Method code:
public MyDisplayMode getElementAt(int index) {
return modes.get(index);
}
No outgoing methods.
jfreerails.client.view.DisplayModesComboBoxModels.getSelectedItem
Javadoc:
No Javadoc available
Method code:
public Object getSelectedItem() {
return selection;
}
No outgoing methods.
jfreerails.client.view.DisplayModesComboBoxModels.getSize
Javadoc:
No Javadoc available
Method code:
public int getSize() {
return modes.size();
}
No outgoing methods.
jfreerails.client.view.DisplayModesComboBoxModels.removeDisplayModesBelow
Javadoc:
/** * Permanently removes from the list in this object any display modes with * width, height, or bitdepth below the specified values. */
Method code:
/**
* Permanently removes from the list in this object any display modes with
* width, height, or bitdepth below the specified values.
*/
public void removeDisplayModesBelow(int width, int height, int bitdepth) {
Iterator<MyDisplayMode> it = modes.iterator();
while (it.hasNext()) {
MyDisplayMode mode = it.next();
DisplayMode displayMode = mode.displayMode;
final boolean tooNarrow = displayMode.getWidth() < width;
final boolean tooShort = displayMode.getHeight() < height;
/*
* Note, displayMode.getBitDepth() may return
* DisplayMode.BIT_DEPTH_MULTI, which is -1.
*/
final boolean tooFewColours = (displayMode.getBitDepth() < bitdepth)
&& (displayMode.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI);
if (tooNarrow || tooShort || tooFewColours) {
it.remove();
}
}
}
No outgoing methods.
jfreerails.client.view.DisplayModesComboBoxModels.removeListDataListener
Javadoc:
No Javadoc available
Method code:
public void removeListDataListener(javax.swing.event.ListDataListener l) {
}
No outgoing methods.
jfreerails.client.view.DisplayModesComboBoxModels.setSelectedItem
Javadoc:
No Javadoc available
Method code:
public void setSelectedItem(Object anItem) {
selection = (MyDisplayMode) anItem;
}
No outgoing methods.
jfreerails.client.view.FreerailsCursor.paintCursor
Javadoc:
/** * Paints the cursor. The method calculates position to paint it based on * the tile size and the cursor's map position. * * @param g * The graphics object to paint the cursor on. * @param tileSize * The dimensions of a tile. */
Method code:
/**
* Paints the cursor. The method calculates position to paint it based on
* the tile size and the cursor's map position.
*
* @param g
* The graphics object to paint the cursor on.
* @param tileSize
* The dimensions of a tile.
*/
public void paintCursor(Graphics g, Dimension tileSize) {
Graphics2D g2 = (Graphics2D) g;
TrackMoveProducer.BuildMode buildMode = (TrackMoveProducer.BuildMode) modelRoot
.getProperty(ModelRoot.Property.TRACK_BUILDER_MODE);
ImPoint cursorMapPosition = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.CURSOR_POSITION);
/* Has the cursor moved since we last painted it? */
if (!cursorMapPosition.equals(lastCursorPosition)) {
lastCursorPosition = cursorMapPosition;
timeArrived = System.currentTimeMillis();
}
int x = cursorMapPosition.x * tileSize.width;
int y = cursorMapPosition.y * tileSize.height;
Image cursor = null;
switch (buildMode) {
case BUILD_TRACK:
cursor = buildTrack;
break;
case REMOVE_TRACK:
cursor = removeTrack;
break;
case UPGRADE_TRACK:
cursor = upgradeTrack;
break;
case IGNORE_TRACK:
cursor = infoMode;
break;
case BUILD_STATION:
cursor = buildTrack;
break;
}
Boolean b = (Boolean) modelRoot
.getProperty(ModelRoot.Property.IGNORE_KEY_EVENTS);
long time = System.currentTimeMillis() - timeArrived;
boolean show = ((time / 500) % 2) == 0;
if (show && !b.booleanValue()) {
g.drawImage(cursor, x, y, null);
}
// Second, draw a message below the cursor if appropriate.
String message = (String) modelRoot
.getProperty(ModelRoot.Property.CURSOR_MESSAGE);
if (null != message && !message.equals("")) {
int fontSize = 12;
Font font = new Font("Arial", 0, fontSize);
FontRenderContext frc = g2.getFontRenderContext();
TextLayout layout = new TextLayout(message, font, frc);
// We want the message to be centered below the cursor.
float visibleAdvance = layout.getVisibleAdvance();
float textX = (x + (tileSize.width / 2) - (visibleAdvance / 2));
float textY = y + tileSize.height + fontSize + 5;
g.setColor(java.awt.Color.white);
layout.draw(g2, textX, textY);
}
// Draw a big white dot at the target point.
ImPoint targetPoint = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.THINKING_POINT);
if (null != targetPoint) {
time = System.currentTimeMillis();
int dotSize;
if ((time % 500) > 250) {
dotSize = BuildTrackRenderer.BIG_DOT_WIDTH;
} else {
dotSize = BuildTrackRenderer.SMALL_DOT_WIDTH;
}
g.setColor(Color.WHITE);
x = targetPoint.x * tileSize.width + (tileSize.width - dotSize) / 2;
y = targetPoint.y * tileSize.width + (tileSize.height - dotSize)
/ 2;
g.fillOval(x, y, dotSize, dotSize);
}
}
Outgoing Methods (calls):
jfreerails.client.view.HtmlJPanel.doneActionPerformed
Javadoc:
No Javadoc available
Method code:
private void doneActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_doneActionPerformed
// TODO add your handling code here:
}// GEN-LAST:event_doneActionPerformed
No outgoing methods.
jfreerails.client.view.HtmlJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
htmlJLabel = new javax.swing.JLabel();
done = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
setMinimumSize(new java.awt.Dimension(400, 300));
jScrollPane1
.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
htmlJLabel.setFont(new java.awt.Font("Dialog", 0, 12));
htmlJLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
jScrollPane1.setViewportView(htmlJLabel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(jScrollPane1, gridBagConstraints);
done.setText("Close");
done.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
doneActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(done, gridBagConstraints);
}// GEN-END:initComponents
Outgoing Methods (calls):
jfreerails.client.view.HtmlJPanel.loadText
Javadoc:
/** Load the help text from file. */
Method code:
/** Load the help text from file. */
String loadText(final URL htmlUrl) {
try {
InputStream in = htmlUrl.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
new DataInputStream(in)));
String line;
String text = "";
while ((line = br.readLine()) != null) {
text = text + line;
}
return text;
} catch (Exception e) {
e.printStackTrace();
logger.warning(htmlUrl.toString());
return "Couldn't read: " + htmlUrl;
}
}
No outgoing methods.
jfreerails.client.view.HtmlJPanel.populateTokens
Javadoc:
No Javadoc available
Method code:
static String populateTokens(String template, Object context) {
StringTokenizer tokenizer = new StringTokenizer(template, "$");
String output = "";
while (tokenizer.hasMoreTokens()) {
output += tokenizer.nextToken();
if (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
String value;
if (context instanceof HashMap) {
value = (String) ((HashMap) context).get(token);
} else {
try {
StringTokenizer t2 = new StringTokenizer(token, ".");
value = null;
Object o = context;
while (t2.hasMoreTokens()) {
String subToken = t2.nextToken();
Field field = o.getClass().getField(subToken);
o = field.get(o);
}
value = o.toString();
} catch (Exception e) {
e.printStackTrace();
throw new NoSuchElementException(token);
}
}
output += value;
}
}
return output;
}
No outgoing methods.
jfreerails.client.view.HtmlJPanel.setHtml
Javadoc:
No Javadoc available
Method code:
void setHtml(String s) {
htmlJLabel.setText(s);
}
No outgoing methods.
jfreerails.client.view.HtmlJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot m, RenderersRoot vl,
Action closeAction) {
this.done.setAction(closeAction);
}
No outgoing methods.
jfreerails.client.view.HtmlJPanelTest.testPopulateTokens
Javadoc:
No Javadoc available
Method code:
public void testPopulateTokens() {
String template = "test";
HashMap<String, String> context = new HashMap<String, String>();
String output = HtmlJPanel.populateTokens(template, context);
assertEquals(template, output);
template = "Hello $name$, $question$";
context.put("name", "Luke");
context.put("question", "how are you?");
String expectedOutput = "Hello Luke, how are you?";
output = HtmlJPanel.populateTokens(template, context);
assertEquals(expectedOutput, output);
Object objectContext = new Object() {
@SuppressWarnings("unused")
public String name = "Luke";
@SuppressWarnings("unused")
public String question = "how are you?";
};
output = HtmlJPanel.populateTokens(template, objectContext);
assertEquals(expectedOutput, output);
}
Outgoing Methods (calls):
jfreerails.client.view.HtmlJPanelTest.testPopulateTokens2
Javadoc:
No Javadoc available
Method code:
public void testPopulateTokens2(){
String template = "Hey $a.name$ I would like you to meet $b.name$";
String expectedOutput = "Hey Tom I would like you to meet Claire";
Object objectContext = new Object() {
@SuppressWarnings("unused")
public Person a = new Person("Tom");
@SuppressWarnings("unused")
public Person b = new Person("Claire");
};
String output = HtmlJPanel.populateTokens(template, objectContext);
assertEquals(expectedOutput, output);
}
Outgoing Methods (calls):
jfreerails.client.view.IncomeStatementGenerator.calRevenue
Javadoc:
/** Calculates the total revenue from the specified cargo type. */
Method code:
/** Calculates the total revenue from the specified cargo type. */
Money calRevenue(Categories cargoCategory) {
long amount = 0;
for (int i = 0; i < w.getNumberOfTransactions(this.principal); i++) {
Transaction t = w.getTransaction(principal, i);
GameTime time = w.getTransactionTimeStamp(principal, i);
if (t instanceof DeliverCargoReceipt
&& cal.getYear(time.getTicks()) >= this.startyear) {
DeliverCargoReceipt dcr = (DeliverCargoReceipt) t;
int cargoType = dcr.getCb().getCargoType();
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, cargoType);
if (ct.getCategory().equals(cargoCategory)) {
amount += dcr.deltaCash().getAmount();
}
}
}
return new Money(amount);
}
Outgoing Methods (calls):
jfreerails.client.view.IncomeStatementGenerator.calTotal
Javadoc:
No Javadoc available
Method code:
private Money calTotal(Transaction.Category transactionCategory) {
long amount = 0;
for (int i = 0; i < w.getNumberOfTransactions(this.principal); i++) {
Transaction t = w.getTransaction(principal, i);
GameTime time = w.getTransactionTimeStamp(principal, i);
if (t.getCategory() == transactionCategory
&& cal.getYear(time.getTicks()) >= this.startyear) {
amount += t.deltaCash().getAmount();
}
}
return new Money(amount);
}
Outgoing Methods (calls):
jfreerails.client.view.IncomeStatementGenerator.calTrainRevenue
Javadoc:
No Javadoc available
Method code:
Money calTrainRevenue(int trainId) {
long amount = 0;
for (int i = 0; i < w.getNumberOfTransactions(this.principal); i++) {
Transaction t = w.getTransaction(principal, i);
GameTime time = w.getTransactionTimeStamp(principal, i);
if (t instanceof DeliverCargoReceipt
&& cal.getYear(time.getTicks()) >= this.startyear) {
DeliverCargoReceipt dcr = (DeliverCargoReceipt) t;
if (dcr.getTrainId() == trainId) {
amount += dcr.deltaCash().getAmount();
}
}
}
return new Money(amount);
}
Outgoing Methods (calls):
jfreerails.client.view.IncomeStatementGeneratorTest.addTrans
Javadoc:
/** * Adds a transaction for a cargo type with the specified category. * Iterates through all cargo types in the world, checks if their category * matches the given category. If a match is found, creates a CargoBatch * and adds a transaction using the specified amount and other parameters. * If no matching category is found, throws an IllegalArgumentException. * * @param category The category of the cargo type to which the transaction applies. * @param amount The monetary amount of the transaction. * @throws IllegalArgumentException if no cargo type matches the specified category. */
Method code:
private void addTrans(Categories category, Money amount) {
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, i);
if (ct.getCategory().equals(category)) {
CargoBatch cb = new CargoBatch(i, 0, 0, 0, 0);
w.addTransaction(MapFixtureFactory.TEST_PRINCIPAL,
new DeliverCargoReceipt(amount, 10, 0, cb, 1));
return;
}
}
throw new IllegalArgumentException(category.toString());
}
Outgoing Methods (calls):
jfreerails.client.view.IncomeStatementGeneratorTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
w = new WorldImpl();
w.addPlayer(MapFixtureFactory.TEST_PLAYER);
MapFixtureFactory.generateCargoTypesList(w);
balanceSheetGenerator = new IncomeStatementGenerator(w,
MapFixtureFactory.TEST_PRINCIPAL);
}
Outgoing Methods (calls):
jfreerails.client.view.IncomeStatementGeneratorTest.testCalExpense
Javadoc:
/** * Tests the {@code calRevenue} method of the balance sheet generator to ensure * it correctly calculates revenue based on the specified category. * <p> * This test performs the following steps: * 1. Verifies that the initial revenue for the "Mail" category is zero. * 2. Adds two transactions: one for the "Mail" category and another for "Passengers". * 3. Confirms that the revenue for the "Mail" category matches the expected amount * after the transactions are processed. * * @param balanceSheetGenerator The instance of the balance sheet generator * under test. * @param w The world context used to retrieve cargo type information. */
Method code:
public void testCalExpense() {
Categories mail = Categories.Mail;
Money m = balanceSheetGenerator.calRevenue(mail);
assertEquals(0, m.getAmount());
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, 0);
assertEquals(mail, ct.getCategory());
Money amount = new Money(100);
addTrans(mail, amount);
addTrans(Categories.Passengers, amount);
m = balanceSheetGenerator.calRevenue(mail);
assertEquals(amount, m);
}
Outgoing Methods (calls):
jfreerails.client.view.IncomeStatementHtmlJPanel.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(Graphics g) {
/* Check to see if the text needs updating before painting. */
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
int currentNumberOfTransactions = world
.getNumberOfTransactions(playerPrincipal);
if (currentNumberOfTransactions != lastNumTransactions) {
updateHtml();
}
super.paintComponent(g);
}
Outgoing Methods (calls):
jfreerails.client.view.IncomeStatementHtmlJPanel.setup
Javadoc:
No Javadoc available
Method code:
@Override
public void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
super.setup(modelRoot, vl, closeAction);
this.modelRoot = modelRoot;
updateHtml();
}
Outgoing Methods (calls):
jfreerails.client.view.IncomeStatementHtmlJPanel.updateHtml
Javadoc:
No Javadoc available
Method code:
private void updateHtml() {
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
IncomeStatementGenerator balanceSheetGenerator = new IncomeStatementGenerator(
world, playerPrincipal);
String populatedTemplate = populateTokens(template,
balanceSheetGenerator);
setHtml(populatedTemplate);
}
Outgoing Methods (calls):
jfreerails.client.view.KeyCode2OneTileMoveVector.getInstanceMappedToKey
Javadoc:
/** Returns the OneTileMoveVector that is mapped to the specified keycode. */
Method code:
/** Returns the OneTileMoveVector that is mapped to the specified keycode. */
public static Step getInstanceMappedToKey(int keycode)
throws NoSuchElementException {
Integer integer = new Integer(keycode);
if (!keycode2vector.containsKey(integer)) {
throw new NoSuchElementException(String.valueOf(keycode));
}
return keycode2vector.get(integer);
}
No outgoing methods.
jfreerails.client.view.LeaderBoardJPanel.getPlayersList
Javadoc:
/** * This method initializes jList * * @return javax.swing.JList */
Method code:
/**
* This method initializes jList
*
* @return javax.swing.JList
*/
private JList getPlayersList() {
if (playersList == null) {
playersList = new JList();
playersList
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
playersList.setRequestFocusEnabled(false);
playersList.setEnabled(true);
Collections.sort(values);
playersList.setListData(values);
}
return playersList;
}
No outgoing methods.
jfreerails.client.view.LeaderBoardJPanel.initialize
Javadoc:
/** * This method initializes this */
Method code:
/**
* This method initializes this
*/
private void initialize() {
this.add(getPlayersList(), null);
java.awt.event.MouseAdapter mouseAdapter = new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
if (null == submitButtonCallBack) {
System.err.println("mouseClicked");
} else {
submitButtonCallBack.actionPerformed(new ActionEvent(
this, 0, null));
}
}
};
this.addMouseListener(mouseAdapter);
this.playersList.addMouseListener(mouseAdapter);
this.setSize(getPreferredSize());
}
Outgoing Methods (calls):
jfreerails.client.view.LeaderBoardJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
ReadOnlyWorld w = modelRoot.getWorld();
values.clear();
this.submitButtonCallBack = closeAction;
for (int player = 0; player < w.getNumberOfPlayers(); player++) {
PlayerDetails details = new PlayerDetails();
FreerailsPrincipal principal = w.getPlayer(player).getPrincipal();
details.name = principal.getName();
NonNullElements stations = new NonNullElements(KEY.STATIONS, w,
principal);
details.stations = stations.size();
TransactionAggregator networth = new NetWorthCalculator(
w, principal);
details.networth = networth.calculateValue();
values.add(details);
}
Collections.sort(values);
playersList.setListData(values);
setSize(getPreferredSize());
}
Outgoing Methods (calls):
jfreerails.client.view.LoadGameAction.actionPerformed
Javadoc:
No Javadoc available
Method code:
public void actionPerformed(ActionEvent e) {
dbc.showSelectSavedGame2Load();
/*
ImStringList files = (ImStringList)modelRoot.getProperty(Property.SAVED_GAMES_LIST);
Object[] saves = new Object[files.size()];
for (int i = 0; i < files.size(); i++) {
saves[i] = files.get(i);
}
// Display a JOptionPane that lists the existing saved games
try {
Object showInputDialog = JOptionPane.showInputDialog(null,
"Saved Games:", "Select game to load",
JOptionPane.INFORMATION_MESSAGE, null, saves, saves[0]);
String filename = showInputDialog.toString();
// Load the game chosen
Message2Server message2 = new LoadGameMessage2Server(1,
filename);
modelRoot.sendCommand(message2);
} catch (Exception exept) {
// <Hack>
// When no saved game is selected, or one that doesnt exist,
// nothing changes
// </.Hack>
}
*/
}
Outgoing Methods (calls):
jfreerails.client.view.LoadGameJPanel.cancelButtonActionPerformed
Javadoc:
/** * Handles the action event triggered when the cancel button is pressed. * If the {@code close} object is not null, this method delegates the action * to the {@code close}'s actionPerformed method with the provided event. * * @param evt the {@code ActionEvent} triggered by the cancel button action */
Method code:
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
if(null != close)
close.actionPerformed(evt);
}//GEN-LAST:event_cancelButtonActionPerformed
No outgoing methods.
jfreerails.client.view.LoadGameJPanel.formComponentShown
Javadoc:
No Javadoc available
Method code:
private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
}//GEN-LAST:event_formComponentShown
No outgoing methods.
jfreerails.client.view.LoadGameJPanel.initComponents
Javadoc:
/** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */
Method code:
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jLabel1 = new javax.swing.JLabel();
okButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
refreshButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jScrollPane1.setViewportView(jList1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(jScrollPane1, gridBagConstraints);
jLabel1.setText("Please select a game to load.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(jLabel1, gridBagConstraints);
okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(okButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(cancelButton, gridBagConstraints);
refreshButton.setText("Refresh");
refreshButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
refreshButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(refreshButton, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
Outgoing Methods (calls):
jfreerails.client.view.LoadGameJPanel.jList1ValueChanged
Javadoc:
No Javadoc available
Method code:
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
okButton.setEnabled(jList1.getSelectedIndex() != -1);
}//GEN-LAST:event_jList1ValueChanged
No outgoing methods.
jfreerails.client.view.LoadGameJPanel.okButtonActionPerformed
Javadoc:
No Javadoc available
Method code:
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
String filename = (String)jList1.getSelectedValue();
Message2Server message2 = new LoadGameMessage2Server(1,
filename);
modelRoot.sendCommand(message2);
if(null != close)
close.actionPerformed(evt);
}//GEN-LAST:event_okButtonActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.LoadGameJPanel.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(Graphics g) {
ImStringList files = (ImStringList) modelRoot.getProperty(Property.SAVED_GAMES_LIST);
if(!lastFiles.equals(files)){
updateListOfFiles();
}
super.paintComponent(g);
}
Outgoing Methods (calls):
jfreerails.client.view.LoadGameJPanel.refreshButtonActionPerformed
Javadoc:
No Javadoc available
Method code:
private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
Message2Server refreshGames = new RefreshListOfGamesMessage2Server(2);
modelRoot.sendCommand(refreshGames);
}//GEN-LAST:event_refreshButtonActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.LoadGameJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot m, RenderersRoot vl, Action closeAction) {
this.close = closeAction;
modelRoot = m;
updateListOfFiles();
}
Outgoing Methods (calls):
jfreerails.client.view.LoadGameJPanel.updateListOfFiles
Javadoc:
No Javadoc available
Method code:
private void updateListOfFiles() {
ImStringList files = (ImStringList) modelRoot.getProperty(Property.SAVED_GAMES_LIST);
Object[] saves = new Object[files.size()];
for (int i = 0; i < files.size(); i++) {
saves[i] = files.get(i);
}
jList1.setListData(saves);
okButton.setEnabled(jList1.getSelectedIndex() != -1);
lastFiles = files;
}
Outgoing Methods (calls):
jfreerails.client.view.MainMapAndOverviewMapMediator.mouseClicked
Javadoc:
/** * Handles mouse click events on the overview map. Converts the click coordinates * to the corresponding position on the main map based on their relative sizes, * scrolls the main map to that position, and triggers an update of the internal * state via the {@code updateInside} method. * * @param evt the mouse event triggered by the user's click on the overview map */
Method code:
@Override
public void mouseClicked(MouseEvent evt) {
/*
* Rectangle r= overviewMapJPanel.mainMapVisibleRect;
* r.x=evt.getX()-r.width/2; r.y=evt.getY()-r.width/2;
*/
// float overviewScale=overviewMapJPanel.getScale();
// float mainMapScale=mainMap.getScale();
int overviewScale = overviewMapJPanel.getPreferredSize().width;
int mainMapScale = mainMap.getWidth();
int x = (evt.getX() * mainMapScale / overviewScale);
int y = (evt.getY() * mainMapScale / overviewScale);
Rectangle r = mainMap.getVisibleRect();
r.x = x - r.width / 2;
r.y = y - r.height / 2;
mainMap.scrollRectToVisible(r);
updateInside(evt);
}
Outgoing Methods (calls):
jfreerails.client.view.MainMapAndOverviewMapMediator.mouseDragged
Javadoc:
No Javadoc available
Method code:
@Override
public void mouseDragged(MouseEvent evt) {
if (draggingAndStartedInside) {
/*
* Rectangle r= overviewMapJPanel.mainMapVisibleRect;
* r.x+=evt.getX()-lastMouseLocation.x;
* r.y+=evt.getY()-lastMouseLocation.y;
* lastMouseLocation.x=evt.getX(); lastMouseLocation.y=evt.getY();
*
* updateInside(evt); overviewMapJPanel.repaint();
*/
int deltaX = evt.getX() - lastMouseLocation.x;
int deltaY = evt.getY() - lastMouseLocation.y;
lastMouseLocation.x = evt.getX();
lastMouseLocation.y = evt.getY();
// float overviewScale=overviewMapJPanel.getScale();
// float mainMapScale=mainMap.getScale();
int overviewScale = overviewMapJPanel.getPreferredSize().width;
int mainMapScale = mainMap.getWidth();
int scaledDeltaX = (deltaX * mainMapScale / overviewScale);
int scaledDeltaY = (deltaY * mainMapScale / overviewScale);
Rectangle r = mainMap.getVisibleRect();
r.x += scaledDeltaX;
r.y += scaledDeltaY;
mainMap.scrollRectToVisible(r);
updateInside(evt);
}
}
Outgoing Methods (calls):
jfreerails.client.view.MainMapAndOverviewMapMediator.mouseMoved
Javadoc:
No Javadoc available
Method code:
@Override
public void mouseMoved(MouseEvent evt) {
lastMouseLocation.x = evt.getX();
lastMouseLocation.y = evt.getY();
updateInside(evt);
}
Outgoing Methods (calls):
jfreerails.client.view.MainMapAndOverviewMapMediator.mousePressed
Javadoc:
No Javadoc available
Method code:
@Override
public void mousePressed(MouseEvent evt) {
if (inside) {
draggingAndStartedInside = true;
}
}
No outgoing methods.
jfreerails.client.view.MainMapAndOverviewMapMediator.mouseReleased
Javadoc:
/** * Ends the drag operation by resetting the dragging state flag. * This method is called when a mouse button is released, indicating * that the drag interaction has concluded. * * @param evt The MouseEvent that triggered this method, providing * details about the mouse release action. */
Method code:
@Override
public void mouseReleased(MouseEvent evt) {
draggingAndStartedInside = false;
}
No outgoing methods.
jfreerails.client.view.MainMapAndOverviewMapMediator.setup
Javadoc:
No Javadoc available
Method code:
public void setup(JComponent omv, JViewport v, JComponent mm, Rectangle rect) {
currentVisRect = rect;
overviewMapJPanel = omv;
viewport = v;
mainMap = mm;
overviewMapJPanel.addMouseMotionListener(this);
overviewMapJPanel.addMouseListener(this);
viewport.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(ChangeEvent e) {
updateObservedRect();
}
});
overviewMapJPanel
.addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(
java.awt.event.ComponentEvent evt) {
updateObservedRect();
}
@Override
public void componentShown(java.awt.event.ComponentEvent evt) {
updateObservedRect();
}
});
}
Outgoing Methods (calls):
jfreerails.client.view.MainMapAndOverviewMapMediator.updateInside
Javadoc:
No Javadoc available
Method code:
private void updateInside(MouseEvent evt) {
// Rectangle r= overviewMapJPanel.mainMapVisibleRect;
boolean b = currentVisRect.contains(evt.getX(), evt.getY());
if (b != inside) {
inside = b;
if (inside) {
overviewMapJPanel.setCursor(new Cursor(Cursor.MOVE_CURSOR));
} else {
overviewMapJPanel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
}
No outgoing methods.
jfreerails.client.view.MainMapAndOverviewMapMediator.updateObservedRect
Javadoc:
No Javadoc available
Method code:
private void updateObservedRect() {
Rectangle r = mainMap.getVisibleRect();
// if (!r.equals(this.currentVisRect)) {
// float overviewScale=overviewMapJPanel.getScale();
// float mainMapScale=mainMap.getScale();
int overviewScale = overviewMapJPanel.getPreferredSize().width;
int mainMapScale = mainMap.getWidth();
if (0 != (overviewScale * mainMapScale)) {
// avoid division by zero.
currentVisRect.x = (r.x * overviewScale / mainMapScale);
currentVisRect.y = (r.y * overviewScale / mainMapScale);
currentVisRect.width = (r.width * overviewScale / mainMapScale);
currentVisRect.height = (r.height * overviewScale / mainMapScale);
overviewMapJPanel.repaint();
}
// }
}
No outgoing methods.
jfreerails.client.view.MapViewJComponent.centerOnTile
Javadoc:
/** * Centers the view on the specified tile coordinates. * * @param tile the tile coordinates to center the view on */
Method code:
public void centerOnTile(Point tile) {
float scale = getMapView().getScale();
Rectangle visRect = new Rectangle(this.getVisibleRect());
visRect.x = (int) (tile.x * scale - (visRect.width / 2));
visRect.y = (int) (tile.y * scale - (visRect.height / 2));
this.scrollRectToVisible(visRect);
}
Outgoing Methods (calls):
jfreerails.client.view.MapViewJComponent.getMapSizeInPixels
Javadoc:
No Javadoc available
Method code:
public Dimension getMapSizeInPixels() {
return getMapView().getMapSizeInPixels();
}
Outgoing Methods (calls):
jfreerails.client.view.MapViewJComponent.getMapView
Javadoc:
No Javadoc available
Method code:
public MapRenderer getMapView() {
return mapView;
}
No outgoing methods.
jfreerails.client.view.MapViewJComponent.getPreferredScrollableViewportSize
Javadoc:
/** * Gets the preferredScrollableViewportSize attribute of the * MapViewJComponent object. * * @return The preferredScrollableViewportSize value */
Method code:
/**
* Gets the preferredScrollableViewportSize attribute of the
* MapViewJComponent object.
*
* @return The preferredScrollableViewportSize value
*/
public java.awt.Dimension getPreferredScrollableViewportSize() {
return this.getPreferredSize();
}
Outgoing Methods (calls):
jfreerails.client.view.MapViewJComponent.getPreferredSize
Javadoc:
No Javadoc available
Method code:
@Override
public Dimension getPreferredSize() {
return getMapSizeInPixels();
}
Outgoing Methods (calls):
jfreerails.client.view.MapViewJComponent.getScale
Javadoc:
No Javadoc available
Method code:
public float getScale() {
return getMapView().getScale();
}
Outgoing Methods (calls):
jfreerails.client.view.MapViewJComponent.getScrollableBlockIncrement
Javadoc:
No Javadoc available
Method code:
public int getScrollableBlockIncrement(java.awt.Rectangle rectangle,
int orientation, int direction) {
if (javax.swing.SwingConstants.VERTICAL == orientation) {
int best = (int) (((rectangle.height / getMapView().getScale()) - 2) * getMapView()
.getScale());
if (best > 0) {
return best;
}
return rectangle.height;
}
float f = ((rectangle.width / getMapView().getScale()) - 2)
* getMapView().getScale();
int best = (int) (f);
if (best > 0) {
return best;
}
return rectangle.width;
}
Outgoing Methods (calls):
jfreerails.client.view.MapViewJComponent.getScrollableTracksViewportHeight
Javadoc:
/** * Gets the scrollableTracksViewportHeight attribute of the * MapViewJComponent object. * * @return The scrollableTracksViewportHeight value */
Method code:
/**
* Gets the scrollableTracksViewportHeight attribute of the
* MapViewJComponent object.
*
* @return The scrollableTracksViewportHeight value
*/
public boolean getScrollableTracksViewportHeight() {
return false;
}
No outgoing methods.
jfreerails.client.view.MapViewJComponent.getScrollableTracksViewportWidth
Javadoc:
No Javadoc available
Method code:
public boolean getScrollableTracksViewportWidth() {
return false;
}
No outgoing methods.
jfreerails.client.view.MapViewJComponent.getScrollableUnitIncrement
Javadoc:
No Javadoc available
Method code:
public int getScrollableUnitIncrement(java.awt.Rectangle rectangle,
int orientation, int direction) {
return (int) getMapView().getScale();
}
Outgoing Methods (calls):
jfreerails.client.view.MapViewJComponent.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(java.awt.Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
java.awt.Rectangle r = this.getVisibleRect();
getMapView().paintRect(g2, r);
}
Outgoing Methods (calls):
jfreerails.client.view.MapViewJComponent.setMapView
Javadoc:
No Javadoc available
Method code:
void setMapView(MapRenderer mapView) {
this.mapView = mapView;
}
No outgoing methods.
jfreerails.client.view.MapViewJComponentConcrete.getMapCursor
Javadoc:
No Javadoc available
Method code:
public FreerailsCursor getMapCursor() {
return mapCursor;
}
No outgoing methods.
jfreerails.client.view.MapViewJComponentConcrete.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
if (null != mapCursor && this.isFocusOwner()) {
mapCursor.paintCursor(g, new java.awt.Dimension(30, 30));
}
if (System.currentTimeMillis() < this.displayMessageUntil) {
Rectangle visRect = this.getVisibleRect();
g.setColor(Color.WHITE);
g.setFont(USER_MESSAGE_FONT);
for (int i = 0; i < userMessage.length; i++) {
g.drawString(this.userMessage[i], 50 + visRect.x, 50
+ visRect.y + i * 20);
}
}
if (message != null) {
Rectangle visRect = this.getVisibleRect();
g.setColor(Color.lightGray);
g.setFont(LARGE_MESSAGE_FONT);
int msgWidth = g.getFontMetrics(LARGE_MESSAGE_FONT).stringWidth(
message);
int msgHeight = g.getFontMetrics(LARGE_MESSAGE_FONT).getHeight();
g.drawString(message,
(int) (visRect.x + (visRect.getWidth() - msgWidth) / 2),
(int) (visRect.y + (visRect.getHeight() - msgHeight) / 2));
}
}
Outgoing Methods (calls):
jfreerails.client.view.MapViewJComponentConcrete.paintRect
Javadoc:
No Javadoc available
Method code:
public void paintRect(Graphics g, Rectangle visibleRect) {
throw new UnsupportedOperationException();
}
No outgoing methods.
jfreerails.client.view.MapViewJComponentConcrete.paintTile
Javadoc:
No Javadoc available
Method code:
public void paintTile(Graphics g, int tileX, int tileY) {
throw new UnsupportedOperationException();
}
No outgoing methods.
jfreerails.client.view.MapViewJComponentConcrete.println
Javadoc:
No Javadoc available
Method code:
private void println(String s) {
StringTokenizer st = new StringTokenizer(s, "\n");
this.userMessage = new String[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
userMessage[i] = st.nextToken();
i++;
}
// Display the message for 5 seconds.
displayMessageUntil = System.currentTimeMillis() + 1000 * 5;
}
No outgoing methods.
jfreerails.client.view.MapViewJComponentConcrete.propertyChange
Javadoc:
/** * Checks what triggered the specified PropertyChangeEvent and reacts as * follows. * <p> * (1) If it was ModelRoot.CURSOR_POSITION, scrolls the map if necessary. * </p> * <p> * (2) If it was ModelRoot.QUICK_MESSAGE, display or hide the message as * appropriate. * </p> * <p> * (3) If it was ModelRoot.PERMANENT_MESSAGE, display or hide the message as * appropriate. * </p> */
Method code:
/**
* Checks what triggered the specified PropertyChangeEvent and reacts as
* follows.
* <p>
* (1) If it was ModelRoot.CURSOR_POSITION, scrolls the map if necessary.
* </p>
* <p>
* (2) If it was ModelRoot.QUICK_MESSAGE, display or hide the message as
* appropriate.
* </p>
* <p>
* (3) If it was ModelRoot.PERMANENT_MESSAGE, display or hide the message as
* appropriate.
* </p>
*/
public void propertyChange(ModelRoot.Property p, Object before, Object after) {
if (p.equals(ModelRoot.Property.CURSOR_POSITION)) {
ImPoint newPoint = (ImPoint) after;
ImPoint oldPoint = (ImPoint) before;
if (null == oldPoint) {
oldPoint = new ImPoint();
}
react2cursorMove(newPoint, oldPoint);
} else if (p.equals(ModelRoot.Property.QUICK_MESSAGE)) {
String newMessage = (String) after;
if (null != newMessage) {
println(newMessage);
} else {
// Its null, so stop displaying whatever we where displaying.
displayMessageUntil = Long.MIN_VALUE;
}
} else if (p.equals(ModelRoot.Property.PERMANENT_MESSAGE)) {
message = (String) after;
}
}
Outgoing Methods (calls):
jfreerails.client.view.MapViewJComponentConcrete.react2cursorMove
Javadoc:
No Javadoc available
Method code:
private void react2cursorMove(ImPoint newPoint, ImPoint oldPoint) {
float scale = getMapView().getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
Rectangle vr = this.getVisibleRect();
Rectangle rectangleSurroundingCursor = new Rectangle(0, 0, 1, 1);
rectangleSurroundingCursor.setLocation((newPoint.x - 1)
* tileSize.width, (newPoint.y - 1) * tileSize.height);
rectangleSurroundingCursor.setSize(tileSize.width * 3,
tileSize.height * 3);
if (!(vr.contains(rectangleSurroundingCursor))) {
int x = newPoint.x * tileSize.width - vr.width / 2;
int y = newPoint.y * tileSize.height - vr.height / 2;
this.scrollRectToVisible(new Rectangle(x, y, vr.width, vr.height));
}
this.repaint((newPoint.x - 1) * tileSize.width, (newPoint.y - 1)
* tileSize.height, tileSize.width * 3, tileSize.height * 3);
this.repaint((oldPoint.x - 1) * tileSize.width, (oldPoint.y - 1)
* tileSize.height, tileSize.width * 3, tileSize.height * 3);
}
Outgoing Methods (calls):
jfreerails.client.view.MapViewJComponentConcrete.refreshAll
Javadoc:
No Javadoc available
Method code:
public void refreshAll() {
this.getMapView().refreshAll();
}
Outgoing Methods (calls):
jfreerails.client.view.MapViewJComponentConcrete.refreshTile
Javadoc:
No Javadoc available
Method code:
public void refreshTile(int x, int y) {
throw new UnsupportedOperationException();
}
No outgoing methods.
jfreerails.client.view.MapViewJComponentConcrete.setup
Javadoc:
No Javadoc available
Method code:
public void setup(MapRenderer mv) {
super.setMapView(mv);
}
Outgoing Methods (calls):
jfreerails.client.view.MapViewJComponentMouseAdapter.mouseDragged
Javadoc:
No Javadoc available
Method code:
@Override
public void mouseDragged(MouseEvent evt) {
if (SwingUtilities.isRightMouseButton(evt)) {
sigmadelta.x += evt.getX() - lastMouseLocation.x;
sigmadelta.y += evt.getY() - lastMouseLocation.y;
int tileSize = (int) getScale();
tiledelta.x = (sigmadelta.x * GRANULARITY) / tileSize;
tiledelta.y = (sigmadelta.y * GRANULARITY) / tileSize;
tiledelta.x = ((tiledelta.x * tileSize) / GRANULARITY)
* LINEAR_ACCEL;
tiledelta.y = ((tiledelta.y * tileSize) / GRANULARITY)
* LINEAR_ACCEL;
Rectangle vr = MapViewJComponentConcrete.this.getVisibleRect();
Rectangle bounds = MapViewJComponentConcrete.this.getBounds();
int temp; // respect bounds
if ((temp = vr.x - tiledelta.x) < 0) {
sigmadelta.x += temp / LINEAR_ACCEL;
tiledelta.x += temp;
} else if ((temp = (bounds.width) - (vr.x + vr.width)
+ tiledelta.x) < 0) {
sigmadelta.x -= temp / LINEAR_ACCEL;
tiledelta.x -= temp;
}
if ((temp = vr.y - tiledelta.y) < 0) {
sigmadelta.y += temp / LINEAR_ACCEL;
tiledelta.y += temp;
} else if ((temp = (bounds.height) - (vr.y + vr.height)
+ tiledelta.y) < 0) {
sigmadelta.y -= temp / LINEAR_ACCEL;
tiledelta.y -= temp;
}
if (tiledelta.x != 0 || tiledelta.y != 0) {
vr.x -= tiledelta.x;
vr.y -= tiledelta.y;
MapViewJComponentConcrete.this.scrollRectToVisible(vr);
sigmadelta.x -= tiledelta.x / LINEAR_ACCEL;
sigmadelta.y -= tiledelta.y / LINEAR_ACCEL;
lastMouseLocation.x -= tiledelta.x;
lastMouseLocation.y -= tiledelta.y;
}
MapViewJComponentConcrete.robot.mouseMove(screenLocation.x,
screenLocation.y);
}
}
Outgoing Methods (calls):
jfreerails.client.view.MapViewJComponentMouseAdapter.mousePressed
Javadoc:
No Javadoc available
Method code:
@Override
public void mousePressed(MouseEvent evt) {
/*
* Note, moving the cursor using the mouse is now handled in
* UserInputOnMapController
*/
if (SwingUtilities.isRightMouseButton(evt)) {
MapViewJComponentConcrete.this
.setCursor(Cursor
.getPredefinedCursor((LINEAR_ACCEL > 0) ? Cursor.HAND_CURSOR
: Cursor.MOVE_CURSOR));
lastMouseLocation.x = evt.getX();
lastMouseLocation.y = evt.getY();
screenLocation.x = evt.getX();
screenLocation.y = evt.getY();
sigmadelta.x = 0;
sigmadelta.y = 0;
javax.swing.SwingUtilities.convertPointToScreen(screenLocation,
MapViewJComponentConcrete.this);
}
}
No outgoing methods.
jfreerails.client.view.MapViewJComponentMouseAdapter.mouseReleased
Javadoc:
No Javadoc available
Method code:
@Override
public void mouseReleased(MouseEvent evt) {
MapViewJComponentConcrete.this.setCursor(Cursor
.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
No outgoing methods.
jfreerails.client.view.NearestStationFinder.findNearestStation
Javadoc:
No Javadoc available
Method code:
public int findNearestStation(int x, int y) {
// Find nearest station.
int distanceToClosestSquared = Integer.MAX_VALUE;
NonNullElements it = new NonNullElements(KEY.STATIONS, world, principal);
int nearestStation = NOT_FOUND;
while (it.next()) {
StationModel station = (StationModel) it.getElement();
int deltaX = x - station.x;
int deltaY = y - station.y;
int distanceSquared = deltaX * deltaX + deltaY * deltaY;
if (distanceSquared < distanceToClosestSquared
&& MAX_DISTANCE_TO_SELECT_SQUARED > distanceSquared) {
distanceToClosestSquared = distanceSquared;
nearestStation = it.getIndex();
}
}
return nearestStation;
}
Outgoing Methods (calls):
jfreerails.client.view.NearestStationFinder.findNearestStationInDirection
Javadoc:
No Javadoc available
Method code:
public int findNearestStationInDirection(int startStation, Step direction) {
int distanceToClosestSquared = Integer.MAX_VALUE;
NonNullElements it = new NonNullElements(KEY.STATIONS, world, principal);
StationModel currentStation = (StationModel) world.get(principal,
KEY.STATIONS, startStation);
int nearestStation = NOT_FOUND;
while (it.next()) {
StationModel station = (StationModel) it.getElement();
int deltaX = station.x - currentStation.x;
int deltaY = station.y - currentStation.y;
int distanceSquared = deltaX * deltaX + deltaY * deltaY;
boolean closer = distanceSquared < distanceToClosestSquared;
boolean notTheSameStation = startStation != it.getIndex();
boolean inRightDirection = isInRightDirection(direction, deltaX,
deltaY);
if (closer && inRightDirection && notTheSameStation) {
distanceToClosestSquared = distanceSquared;
nearestStation = it.getIndex();
}
}
return nearestStation;
}
Outgoing Methods (calls):
jfreerails.client.view.NearestStationFinder.isInRightDirection
Javadoc:
/** * Returns true if the angle between direction and the vector (deltaX, * deltaY) is less than 45 degrees. */
Method code:
/**
* Returns true if the angle between direction and the vector (deltaX,
* deltaY) is less than 45 degrees.
*/
private boolean isInRightDirection(Step direction, int deltaX, int deltaY) {
boolean isDiagonal = direction.deltaX * direction.deltaY != 0;
boolean sameXDirection = (direction.deltaX * deltaX) > 0;
boolean sameYDirection = (direction.deltaY * deltaY > 0);
boolean deltaXisLongerThanDeltaY = deltaX * deltaX < deltaY * deltaY;
if (isDiagonal) {
return sameXDirection && sameYDirection;
}
if (0 == direction.deltaX) {
return deltaXisLongerThanDeltaY && sameYDirection;
}
return !deltaXisLongerThanDeltaY && sameXDirection;
}
No outgoing methods.
jfreerails.client.view.NetWorthGraphJPanel.getYScaleString
Javadoc:
No Javadoc available
Method code:
private String getYScaleString(long value) {
String abv;
if (value >= 1000000000) {
value = value / 1000000000;
abv = "b";
} else if (value >= 1000000) {
value = value / 1000000;
abv = "m";
} else if (value >= 1000) {
value = value / 1000;
abv = "k";
} else {
abv = "";
}
return "$" + String.valueOf(value) + abv;
}
No outgoing methods.
jfreerails.client.view.NetWorthGraphJPanel.initialize
Javadoc:
/** * This method initializes this * */
Method code:
/**
* This method initializes this
*
*/
private void initialize() {
yAxisLabel4 = new JLabel();
yAxisLabel3 = new JLabel();
yAxisLabel2 = new JLabel();
xAxisLabel1 = new JLabel();
xAxisLabel2 = new JLabel();
xAxisLabel3 = new JLabel();
title = new JLabel();
yAxisLabel1 = new JLabel();
this.setLayout(null);
this.setBackground(java.awt.Color.white);
this.setSize(444, 315);
title.setText("Net Worth");
title.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.PLAIN, 24));
title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
title.setLocation(0, 0);
title.setSize(444, 43);
yAxisLabel1.setText("$25");
yAxisLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
yAxisLabel3.setText("$999m");
yAxisLabel4.setText("$999M");
yAxisLabel4.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
yAxisLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
yAxisLabel3.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
yAxisLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
yAxisLabel2.setText("$50");
yAxisLabel2.setLocation(0, 167);
yAxisLabel2.setSize(40, 16);
yAxisLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
yAxisLabel2.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
yAxisLabel1.setLocation(0, 227);
yAxisLabel1.setSize(40, 16);
yAxisLabel3.setLocation(0, 107);
yAxisLabel3.setSize(40, 16);
yAxisLabel4.setLocation(0, 47);
yAxisLabel4.setSize(40, 16);
xAxisLabel3.setText("2000");
xAxisLabel3.setLocation(400, 300);
xAxisLabel3.setSize(40, 17);
xAxisLabel3.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
xAxisLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
xAxisLabel2.setText("1950");
xAxisLabel2.setLocation(210, 300);
xAxisLabel2.setSize(40, 17);
xAxisLabel2.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
xAxisLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
xAxisLabel1.setText("1900");
xAxisLabel1.setLocation(20, 300);
xAxisLabel1.setSize(40, 17);
xAxisLabel1.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
xAxisLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
this.add(xAxisLabel3, null);
this.add(xAxisLabel2, null);
this.add(xAxisLabel1, null);
yAxisLabel1.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
this.add(title, null);
this.add(yAxisLabel1, null);
this.add(yAxisLabel3, null);
this.add(yAxisLabel2, null);
this.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
if (null == submitButtonCallBack) {
System.err.println("mouseClicked");
} else {
submitButtonCallBack.actionPerformed(new ActionEvent(this,
0, null));
}
}
});
this.add(yAxisLabel4, null);
}
No outgoing methods.
jfreerails.client.view.NetWorthGraphJPanel.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(2f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL));
// Draw guide lines.
g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL));
g.setColor(Color.GRAY);
for (int y = 295; y > 50; y -= 60) {
g2.drawLine(graphRect.x, y, 420, y);
}
g2.setStroke(new BasicStroke(2f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL));
// Draw key
for (int i = 0; i < companies.size(); i++) {
int yOffset = i * 20;
CompanyDetails company = companies.get(i);
g2.setColor(company.color);
g2.drawLine(50, 70 + yOffset, 60, 70 + yOffset);
g2.setColor(Color.BLACK);
g2.setFont(FONT);
g.drawString(company.name, 65, 72 + yOffset);
}
// Draw graphs lines
for (int i = 0; i < companies.size(); i++) {
CompanyDetails company = companies.get(i);
g2.setColor(company.color);
for (int year = 1; year < 100; year++) {
if (company.value[year] != Integer.MIN_VALUE
&& company.value[year - 1] != Integer.MIN_VALUE) {
long x1 = year * graphRect.width / 100 + graphRect.x;
long y1 = company.value[year] * graphRect.height / scaleMax;
y1 = Math.max(1, y1);
y1 = graphRect.y + graphRect.height - y1;
long x2 = (year - 1) * graphRect.width / 100 + graphRect.x;
long y2 = company.value[year - 1] * graphRect.height
/ scaleMax;
y2 = Math.max(1, y2);
y2 = graphRect.y + graphRect.height - y2;
g2.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
}
}
}
// Draw axis
g2.setColor(Color.BLACK);
g2.drawLine(graphRect.x, graphRect.y, graphRect.x, graphRect.y
+ graphRect.height);
g2.drawLine(graphRect.x, graphRect.y + graphRect.height, graphRect.x
+ graphRect.width, graphRect.y + graphRect.height);
}
No outgoing methods.
jfreerails.client.view.NetWorthGraphJPanel.setAppropriateScale
Javadoc:
/** * <p> * Sets the value of scaleMax subject to the following constraints. * </P> * <p> * (1) scaleMax >= max, where max is the max net worth value. * </p> * <p> * (2) (scaleMax % 4) == 0 * </p> * <p> * (3) if max >= 1,000, then (scaleMax % 4,000) == 0 * </p> * <p> * (4) if max >= 1,000,000, then (scaleMax % 4,000,000) == 0 * </p> * <p> * (5) if max >= 1,000,000,000, then (scaleMax % 4,000,000,000) == 0 * </p> */
Method code:
/**
* <p>
* Sets the value of scaleMax subject to the following constraints.
* </P>
* <p>
* (1) scaleMax >= max, where max is the max net worth value.
* </p>
* <p>
* (2) (scaleMax % 4) == 0
* </p>
* <p>
* (3) if max >= 1,000, then (scaleMax % 4,000) == 0
* </p>
* <p>
* (4) if max >= 1,000,000, then (scaleMax % 4,000,000) == 0
* </p>
* <p>
* (5) if max >= 1,000,000,000, then (scaleMax % 4,000,000,000) == 0
* </p>
*/
private void setAppropriateScale() {
long max = 0;
for (int i = 0; i < companies.size(); i++) {
CompanyDetails company = companies.get(i);
for (int year = 0; year < 100; year++) {
long value = company.value[year];
if (value > max) {
max = value;
}
}
}
long increment = 1;
while (scaleMax < max) {
scaleMax = increment;
if (scaleMax < max) {
scaleMax += increment;
int loopCount = 0;
while (scaleMax < max && loopCount < 3) {
scaleMax += increment * 2;
loopCount++;
}
}
increment = increment * 10;
}
/*
* Make sure that if the scale is in k/m/b that each of the quarter
* scales will be divisible by k/m/b.
*/
increment = 1;
for (int i = 0; i < 3; i++) {
increment = increment * 1000;
if (scaleMax >= 8 * increment && scaleMax < 12 * increment) {
scaleMax = 12 * increment;
} else if (scaleMax >= 4 * increment && scaleMax < 8 * increment) {
scaleMax = 8 * increment;
} else if (scaleMax >= 1 * increment && scaleMax < 4 * increment) {
scaleMax = 4 * increment;
}
}
if (scaleMax < 100) {
scaleMax = 100;
}
long quarterScale = scaleMax / 4;
yAxisLabel1.setText(getYScaleString(quarterScale));
yAxisLabel2.setText(getYScaleString(quarterScale * 2));
yAxisLabel3.setText(getYScaleString(quarterScale * 3));
yAxisLabel4.setText(getYScaleString(quarterScale * 4));
}
Outgoing Methods (calls):
jfreerails.client.view.NetWorthGraphJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
this.submitButtonCallBack = closeAction;
ReadOnlyWorld world = modelRoot.getWorld();
companies = new ArrayList<CompanyDetails>();
GameCalendar calender = (GameCalendar) world.get(ITEM.CALENDAR);
int startYear = calender.getYear(0);
int endYear = startYear + 100;
GameTime currentTime = world.currentTime();
int currentYear = calender.getYear(currentTime.getTicks());
xAxisLabel1.setText(String.valueOf(startYear));
xAxisLabel2.setText(String.valueOf(startYear + 50));
xAxisLabel3.setText(String.valueOf(endYear));
for (int i = 0; i < world.getNumberOfPlayers(); i++) {
Color c = PlayerColors.getColor(i);
Player player = world.getPlayer(i);
String name = player.getName();
logger.fine("Adding player " + name + " to net worth graph.");
CompanyDetails cd = new CompanyDetails(name, c);
GameTime[] times = new GameTime[101];
for (int year = 0; year < 101; year++) {
int ticks = calender.getTicks(startYear + year - 1);
times[year] = new GameTime(ticks);
}
TransactionAggregator aggregator = new NetWorthCalculator(world,
player.getPrincipal());
aggregator.setTimes(times);
Money[] values = aggregator.calculateValues();
int stopYear = currentYear - startYear + 1;
for (int year = 0; year < stopYear; year++) {
cd.value[year] = values[year].getAmount();
}
companies.add(cd);
}
setAppropriateScale();
}
Outgoing Methods (calls):
jfreerails.client.view.NewGameAction.actionPerformed
Javadoc:
No Javadoc available
Method code:
public void actionPerformed(ActionEvent e) {
String mapName = e.getActionCommand();
if (mapName != null) {
Message2Server message2 = new NewGameMessage2Server(1, mapName);
modelRoot.sendCommand(message2);
}
}
Outgoing Methods (calls):
jfreerails.client.view.NewsPaperJPanel.formKeyPressed
Javadoc:
No Javadoc available
Method code:
// GEN-END:initComponents
private void formKeyPressed(java.awt.event.KeyEvent evt) { // GEN-FIRST:event_formKeyPressed
// Add your handling code here:
this.setVerifyInputWhenFocusTarget(false);
}
No outgoing methods.
jfreerails.client.view.NewsPaperJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the FormEditor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() { // GEN-BEGIN:initComponents
headline = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
anyKeyToContinueJLabel = new javax.swing.JLabel();
setLayout(null);
setPreferredSize(new java.awt.Dimension(640, 400));
setMinimumSize(new java.awt.Dimension(640, 400));
setMaximumSize(new java.awt.Dimension(640, 400));
setOpaque(false);
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
headline.setPreferredSize(new java.awt.Dimension(620, 110));
headline.setMinimumSize(new java.awt.Dimension(620, 110));
headline.setText("NEWSPAPER HEADLINE");
headline.setForeground(java.awt.Color.black);
headline.setBackground(java.awt.Color.white);
headline.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
headline.setFont(new java.awt.Font("Lucida Bright", 1, 36));
headline.setMaximumSize(new java.awt.Dimension(620, 110));
add(headline);
headline.setBounds(10, 70, 620, 110);
jPanel1.setBorder(new javax.swing.border.BevelBorder(0));
anyKeyToContinueJLabel.setText("Click to continue");
anyKeyToContinueJLabel.setForeground(java.awt.Color.black);
anyKeyToContinueJLabel.setBackground(java.awt.Color.darkGray);
jPanel1.add(anyKeyToContinueJLabel);
add(jPanel1);
jPanel1.setBounds(230, 260, 190, 30);
}
Outgoing Methods (calls):
jfreerails.client.view.NewsPaperJPanel.paint
Javadoc:
No Javadoc available
Method code:
// GEN-LAST:event_formKeyPressed
@Override
public void paint(Graphics g) {
g.drawImage(this.pieceOfNewspaper, 0, 0, null);
this.paintChildren(g);
}
No outgoing methods.
jfreerails.client.view.NewsPaperJPanel.setHeadline
Javadoc:
No Javadoc available
Method code:
public void setHeadline(String s) {
this.headline.setText(s);
}
No outgoing methods.
jfreerails.client.view.NewsPaperJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
this.callBack = closeAction;
}
No outgoing methods.
jfreerails.client.view.OverHeadTrainView.getTrainRenderer
Javadoc:
No Javadoc available
Method code:
public TrainRenderer getTrainRenderer() {
return trainRenderer;
}
No outgoing methods.
jfreerails.client.view.OverHeadTrainView.paint
Javadoc:
No Javadoc available
Method code:
public void paint(Graphics2D g) {
g.setColor(Color.BLUE);
g.setStroke(new BasicStroke(10));
Double time = (Double)mr.getProperty(Property.TIME);
for (int k = 0; k < w.getNumberOfPlayers(); k++) {
FreerailsPrincipal principal = w.getPlayer(k).getPrincipal();
int selectedTrain = -1;
if (mr.getPrincipal().getWorldIndex() == principal.getWorldIndex()) {
//These are our trains...
Object property = mr.getProperty(Property.SELECTED_TRAIN);
if (null != property) {
selectedTrain = (Integer) property;
}
}
for (int i = 0; i < w.size(principal, KEY.TRAINS); i++) {
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS, i);
// TrainPositionOnMap pos = (TrainPositionOnMap) w.get(
// principal, KEY.TRAIN_POSITIONS, i);
TrainAccessor ta = new TrainAccessor(w, principal, i);
TrainPositionOnMap pos = ta.findPosition(time);
if (pos.isCrashSite()
&& (pos.getFrameCt() <= TrainPositionOnMap.CRASH_FRAMES_COUNT)) {
trainRenderer.paintTrainCrash(g, pos);
if (pos.getFrameCt() == 1) {
try {
soundManager.playSound(
"/jfreerails/client/sounds/traincrash.wav",
1);
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
TrainImages.Highlight highlight = i == selectedTrain ? TrainImages.Highlight.SELECTED: null;
trainRenderer.paintTrain(g, train, pos, highlight);
}
}
}
}
Outgoing Methods (calls):
jfreerails.client.view.OverviewMapJComponent.getPreferredSize
Javadoc:
No Javadoc available
Method code:
@Override
public Dimension getPreferredSize() {
return mapView.getMapSizeInPixels();
}
Outgoing Methods (calls):
jfreerails.client.view.OverviewMapJComponent.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(java.awt.Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
java.awt.Rectangle r = this.getVisibleRect();
mapView.paintRect(g2, r);
g2.setColor(Color.WHITE);
g2.drawRect(mainMapVisRect.x, mainMapVisRect.y, mainMapVisRect.width,
mainMapVisRect.height);
}
Outgoing Methods (calls):
jfreerails.client.view.OverviewMapJComponent.setup
Javadoc:
No Javadoc available
Method code:
public void setup(MapRenderer mv) {
mapView = mv;
this.setPreferredSize(mapView.getMapSizeInPixels());
this.setMinimumSize(this.getPreferredSize());
this.setSize(this.getPreferredSize());
if (null != this.getParent()) {
this.getParent().validate();
}
}
Outgoing Methods (calls):
jfreerails.client.view.PlayerColors.getColor
Javadoc:
No Javadoc available
Method code:
public static Color getColor(int playerNumber) {
return colors[playerNumber % colors.length];
}
No outgoing methods.
jfreerails.client.view.PlayerDetails.compareTo
Javadoc:
No Javadoc available
Method code:
public int compareTo(PlayerDetails test) {
long l = test.networth.getAmount() - networth.getAmount();
return (int) l;
}
Outgoing Methods (calls):
jfreerails.client.view.RHSJTabPane.propertyChange
Javadoc:
/** * Updates the Terrain Info Panel if the specified PropertyChangeEvent was * triggered by the cursor moving. */
Method code:
/**
* Updates the Terrain Info Panel if the specified PropertyChangeEvent was
* triggered by the cursor moving.
*/
public void propertyChange(ModelRoot.Property prop, Object before,
Object after) {
if (prop.equals(ModelRoot.Property.CURSOR_POSITION)) {
ImPoint p = (ImPoint) after;
terrainInfoPanel.setTerrainType(((FreerailsTile) world.getTile(p.x,
p.y)).getTerrainTypeID());
}
}
Outgoing Methods (calls):
jfreerails.client.view.RHSJTabPane.setStationTabEnabled
Javadoc:
No Javadoc available
Method code:
public void setStationTabEnabled(boolean enabled) {
// this.setEnabledAt(this.stationInfoIndex, enabled);
}
No outgoing methods.
jfreerails.client.view.RHSJTabPane.setTrainTabEnabled
Javadoc:
No Javadoc available
Method code:
public void setTrainTabEnabled(boolean enabled) {
this.setEnabledAt(this.trainListIndex, enabled);
}
No outgoing methods.
jfreerails.client.view.RHSJTabPane.setup
Javadoc:
No Javadoc available
Method code:
public void setup(final ActionRoot actionRoot, RenderersRoot vl,
final ModelRootImpl modelRoot) {
world = modelRoot.getWorld();
terrainInfoPanel.setup(world, vl);
stationInfoPanel.setup(modelRoot, vl, null);
ActionListener showTrain = new ActionListener() {
public void actionPerformed(ActionEvent e) {
int id = trainListPanel.getSelectedTrainID();
actionRoot.getDialogueBoxController().showTrainOrders(id);
}
};
trainListPanel.setShowTrainDetailsActionListener(showTrain);
trainListPanel.setup(modelRoot, vl, null);
modelRoot.addPropertyChangeListener(this);
buildTrackPanel.setup(modelRoot, actionRoot, vl, null);
}
Outgoing Methods (calls):
jfreerails.client.view.SaveGameAction.actionPerformed
Javadoc:
No Javadoc available
Method code:
public void actionPerformed(ActionEvent e) {
dbc.showSaveGame();
/*
try {
// @SonnyZ
// Show a JOptionPane that takes in a string from a text box
String filename = JOptionPane.showInputDialog(null,
"Saved Game Name:", "Save Game",
JOptionPane.QUESTION_MESSAGE, null, null,
modelRoot.getPrincipal().getName()).toString();
// Save the current game using the string
modelRoot.setProperty(Property.QUICK_MESSAGE, "Saved game "
+ filename);
Message2Server message2 = new SaveGameMessage2Server(1,
filename + ".sav");
modelRoot.sendCommand(message2);
loadGameAction.setEnabled(true);
} catch (Exception except) {
}
*/
}
Outgoing Methods (calls):
jfreerails.client.view.SaveGameJPanel.cancelButtonActionPerformed
Javadoc:
No Javadoc available
Method code:
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
close.actionPerformed(evt);
}//GEN-LAST:event_cancelButtonActionPerformed
No outgoing methods.
jfreerails.client.view.SaveGameJPanel.fileNameTextFieldActionPerformed
Javadoc:
No Javadoc available
Method code:
private void fileNameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileNameTextFieldActionPerformed
// TODO add your handling code here:
System.out.println("fileNameTextFieldActionPerformed"+evt.toString());
}//GEN-LAST:event_fileNameTextFieldActionPerformed
No outgoing methods.
jfreerails.client.view.SaveGameJPanel.initComponents
Javadoc:
/** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */
Method code:
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jLabel1 = new javax.swing.JLabel();
fileNameTextField = new javax.swing.JTextField();
oKButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
jLabel1.setText("Please enter a name for the save game.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(jLabel1, gridBagConstraints);
fileNameTextField.setText("savegame");
fileNameTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileNameTextFieldActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(fileNameTextField, gridBagConstraints);
oKButton.setText("OK");
oKButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
oKButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(oKButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(cancelButton, gridBagConstraints);
}
Outgoing Methods (calls):
jfreerails.client.view.SaveGameJPanel.oKButtonActionPerformed
Javadoc:
/** * Handles the action event when the OK button is pressed. * Retrieves the filename from the text field, saves the current game * by setting the QUICK_MESSAGE property and sending a SaveGameMessage2Server * command to the model. Also closes the panel. * * @param evt the ActionEvent triggered by the OK button action * @throws Exception if an error occurs during property setting or command sending */
Method code:
private void oKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_oKButtonActionPerformed
String filename = fileNameTextField.getText();
// Save the current game using the string
modelRoot.setProperty(Property.QUICK_MESSAGE, "Saved game "
+ filename);
Message2Server message2 = new SaveGameMessage2Server(1,
filename + ".sav");
modelRoot.sendCommand(message2);
close.actionPerformed(evt);
}//GEN-LAST:event_oKButtonActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.SaveGameJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot m, RenderersRoot vl,
Action closeAction) {
this.close = closeAction;
this.modelRoot = m;
}
No outgoing methods.
jfreerails.client.view.SelectEngineJPanel.getEngineType
Javadoc:
/** * Returns the number of the currently selected engine type. * */
Method code:
/**
* Returns the number of the currently selected engine type.
*
*/
public int getEngineType() {
return jList1.getSelectedIndex();
}
No outgoing methods.
jfreerails.client.view.SelectEngineJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the FormEditor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
okjButton = new javax.swing.JButton();
canceljButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(400, 350));
okjButton.setText("OK");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 9, 10);
add(okjButton, gridBagConstraints);
canceljButton.setText("Cancel");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
add(canceljButton, gridBagConstraints);
jList1
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1
.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(
javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jScrollPane1.setViewportView(jList1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}// GEN-END:initComponents
Outgoing Methods (calls):
jfreerails.client.view.SelectEngineJPanel.jList1ValueChanged
Javadoc:
No Javadoc available
Method code:
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) { // GEN-FIRST:event_jList1ValueChanged
// We need to disable the OK button if no engine type is selected.
if (-1 == jList1.getSelectedIndex()) {
okjButton.setEnabled(false);
} else {
okjButton.setEnabled(true);
}
} // GEN-LAST:event_jList1ValueChanged
No outgoing methods.
jfreerails.client.view.SelectEngineJPanel.setCancelButtonActionListener
Javadoc:
/** * Removes any existing ActionListener listeners from the cancel button, * then adds the specified one. */
Method code:
/**
* Removes any existing ActionListener listeners from the cancel button,
* then adds the specified one.
*/
void setCancelButtonActionListener(ActionListener l) {
ActionListener[] oldListeners = canceljButton.getActionListeners();
for (int i = 0; i < oldListeners.length; i++) {
canceljButton.removeActionListener(oldListeners[i]);
}
this.canceljButton.addActionListener(l);
}
No outgoing methods.
jfreerails.client.view.SelectEngineJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
jList1.setModel(new World2ListModelAdapter(mr.getWorld(),
SKEY.ENGINE_TYPES));
jList1.setCellRenderer(new TrainCellRenderer(vl));
okjButton.addActionListener(closeAction);
}
Outgoing Methods (calls):
jfreerails.client.view.SelectStationJPanel.display
Javadoc:
No Javadoc available
Method code:
public void display(MutableSchedule newSchedule, int orderNumber) {
this.schedule = newSchedule;
this.selectedOrderNumber = orderNumber;
TrainOrdersModel order = newSchedule.getOrder(selectedOrderNumber);
this.selectedStationID = order.getStationID();
// Set the text on the title JLabel.
this.jLabel1.setText("Stop " + String.valueOf(selectedOrderNumber + 1));
// Set the station info panel to show the current selected station.
cargoWaitingAndDemandedJPanel1.display(selectedStationID);
}
Outgoing Methods (calls):
jfreerails.client.view.SelectStationJPanel.formComponentResized
Javadoc:
No Javadoc available
Method code:
private void formComponentResized(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_formComponentResized
setZoom();
}// GEN-LAST:event_formComponentResized
Outgoing Methods (calls):
jfreerails.client.view.SelectStationJPanel.formComponentShown
Javadoc:
No Javadoc available
Method code:
private void formComponentShown(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_formComponentShown
setZoom();
}// GEN-LAST:event_formComponentShown
Outgoing Methods (calls):
jfreerails.client.view.SelectStationJPanel.formKeyPressed
Javadoc:
No Javadoc available
Method code:
private void formKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_formKeyPressed
try {
Step v = KeyCode2OneTileMoveVector.getInstanceMappedToKey(evt
.getKeyCode());
// now find nearest station in direction of the vector.
NearestStationFinder stationFinder = new NearestStationFinder(
this.world, this.principal);
int station = stationFinder.findNearestStationInDirection(
this.selectedStationID, v);
if (selectedStationID != station
&& station != NearestStationFinder.NOT_FOUND) {
selectedStationID = station;
cargoWaitingAndDemandedJPanel1.display(selectedStationID);
this.validate();
this.repaint();
}
} catch (NoSuchElementException e) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
needsUpdating = true;
submitButtonCallBack.actionPerformed(null);
}
// The key pressed isn't mapped to a OneTileMoveVector so do
// nothing.
}
}// GEN-LAST:event_formKeyPressed
Outgoing Methods (calls):
jfreerails.client.view.SelectStationJPanel.formMouseClicked
Javadoc:
No Javadoc available
Method code:
private void formMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_formMouseClicked
formMouseMoved(evt);
needsUpdating = true;
this.submitButtonCallBack.actionPerformed(null);
}// GEN-LAST:event_formMouseClicked
Outgoing Methods (calls):
jfreerails.client.view.SelectStationJPanel.formMouseMoved
Javadoc:
No Javadoc available
Method code:
private void formMouseMoved(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_formMouseMoved
// Add your handling code here:
double x = evt.getX();
x = x / scale + visibleMapTiles.x;
double y = evt.getY();
y = y / scale + visibleMapTiles.y;
NearestStationFinder stationFinder = new NearestStationFinder(
this.world, this.principal);
int station = stationFinder.findNearestStation((int) x, (int) y);
if (selectedStationID != station
&& station != NearestStationFinder.NOT_FOUND) {
selectedStationID = station;
cargoWaitingAndDemandedJPanel1.display(selectedStationID);
this.validate();
this.repaint();
}
}// GEN-LAST:event_formMouseMoved
Outgoing Methods (calls):
jfreerails.client.view.SelectStationJPanel.generateNewSchedule
Javadoc:
No Javadoc available
Method code:
public MutableSchedule generateNewSchedule() {
TrainOrdersModel oldOrders, newOrders;
oldOrders = schedule.getOrder(selectedOrderNumber);
newOrders = new TrainOrdersModel(selectedStationID, oldOrders
.getConsist(), oldOrders.getWaitUntilFull(), oldOrders
.isAutoConsist());
schedule.setOrder(selectedOrderNumber, newOrders);
return schedule;
}
Outgoing Methods (calls):
jfreerails.client.view.SelectStationJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
cargoWaitingAndDemandedJPanel1 = new jfreerails.client.view.CargoWaitingAndDemandedJPanel();
jLabel1 = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(500, 350));
addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
@Override
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
formMouseClicked(evt);
}
});
addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
@Override
public void mouseMoved(java.awt.event.MouseEvent evt) {
formMouseMoved(evt);
}
});
cargoWaitingAndDemandedJPanel1
.setBorder(new javax.swing.border.LineBorder(
new java.awt.Color(0, 0, 0)));
cargoWaitingAndDemandedJPanel1.setPreferredSize(new java.awt.Dimension(
165, 300));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(cargoWaitingAndDemandedJPanel1, gridBagConstraints);
jLabel1.setText("Train #1 Stop 1");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
add(jLabel1, gridBagConstraints);
}// GEN-END:initComponents
Outgoing Methods (calls):
jfreerails.client.view.SelectStationJPanel.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(Graphics g) {
if (needsUpdating) {
this.setZoom();
}
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
NonNullElements it = new NonNullElements(KEY.STATIONS, world,
this.principal);
// Draw track
g2.setColor(Color.BLACK);
for (int x = Math.max(0, visibleMapTiles.x); x < Math.min(
visibleMapTiles.width + visibleMapTiles.x, world.getMapWidth()); x++) {
for (int y = Math.max(0, visibleMapTiles.y); y < Math.min(
visibleMapTiles.height + visibleMapTiles.y, world
.getMapHeight()); y++) {
FreerailsTile tt = (FreerailsTile) world.getTile(x, y);
if (!tt.getTrackPiece().equals(NullTrackPiece.getInstance())) {
double xDouble = x - visibleMapTiles.x;
xDouble = xDouble * scale;
double yDouble = y - visibleMapTiles.y;
yDouble = yDouble * scale;
g.drawRect((int) xDouble, (int) yDouble, 1, 1);
}
}
}
// Draw stations
while (it.next()) {
/*
* (1) The selected station is drawn green. (2) Non-selected
* stations which are on the schedule are drawn blue. (3) Other
* stations are drawn white. (4) If, for instance, station X is the
* first stop on the schedule, "1" is drawn above the station. (5)
* If, for instance, station X is the first and third stop on the
* schedule, "1, 3" is drawn above the station. (6) The stop numbers
* drawn above the stations are drawn using the same colour as used
* to draw the station.
*/
StationModel station = (StationModel) it.getElement();
double x = station.x - visibleMapTiles.x;
x = x * scale;
double y = station.y - visibleMapTiles.y;
y = y * scale;
int xInt = (int) x;
int yInt = (int) y;
String stopNumbersString = "";
boolean stationIsOnSchedule = false;
for (int orderNumber = 0; orderNumber < schedule.getNumOrders(); orderNumber++) {
int stationID = orderNumber == this.selectedOrderNumber ? this.selectedStationID
: schedule.getOrder(orderNumber).getStationID();
if (it.getIndex() == stationID) {
if (stationIsOnSchedule) {
stopNumbersString = stopNumbersString + ", "
+ String.valueOf(orderNumber + 1);
} else {
stopNumbersString = String.valueOf(orderNumber + 1);
}
stationIsOnSchedule = true;
}
}
if (stationIsOnSchedule) {
if (it.getIndex() == selectedStationID) {
g2.setColor(Color.GREEN);
} else {
g2.setColor(Color.BLUE);
}
g2.drawString(stopNumbersString, xInt, yInt - 4);
} else {
g2.setColor(Color.WHITE);
}
g2.fillRect(xInt, yInt, 10, 10);
}
}
Outgoing Methods (calls):
jfreerails.client.view.SelectStationJPanel.setZoom
Javadoc:
/** * Sets the zoom based on the size of the component and the positions of the * stations. */
Method code:
/**
* Sets the zoom based on the size of the component and the positions of the
* stations.
*/
private void setZoom() {
mapRect = this.getBounds();
Rectangle r = cargoWaitingAndDemandedJPanel1.getBounds();
mapRect.width -= r.width;
int topLeftX = Integer.MAX_VALUE;
int topLeftY = Integer.MAX_VALUE;
int bottomRightX = Integer.MIN_VALUE;
int bottomRightY = Integer.MIN_VALUE;
NonNullElements it = new NonNullElements(KEY.STATIONS, world,
this.principal);
while (it.next()) {
StationModel station = (StationModel) it.getElement();
if (station.x < topLeftX)
topLeftX = station.x;
if (station.y < topLeftY)
topLeftY = station.y;
if (station.x > bottomRightX)
bottomRightX = station.x;
if (station.y > bottomRightY)
bottomRightY = station.y;
}
// Add some padding.
topLeftX -= 10;
topLeftY -= 10;
bottomRightX += 10;
bottomRightY += 10;
int width = bottomRightX - topLeftX;
int height = bottomRightY - topLeftY;
visibleMapTiles = new Rectangle(topLeftX, topLeftY, width, height);
boolean heightConstraintBinds = (visibleMapTiles.getHeight() / visibleMapTiles
.getWidth()) > (mapRect.getHeight() / mapRect.getWidth());
if (heightConstraintBinds) {
scale = mapRect.getHeight() / visibleMapTiles.getHeight();
} else {
scale = mapRect.getWidth() / visibleMapTiles.getWidth();
}
needsUpdating = false;
}
Outgoing Methods (calls):
jfreerails.client.view.SelectStationJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
cargoWaitingAndDemandedJPanel1.setup(mr, vl, null);
this.world = mr.getWorld();
this.submitButtonCallBack = closeAction;
principal = mr.getPrincipal();
}
Outgoing Methods (calls):
jfreerails.client.view.SelectWagonsJPanel.addwagon
Javadoc:
No Javadoc available
Method code:
// Adds the wagon selected in the list to the train consist.
private void addwagon() {
if (wagons.size() < TrainModel.MAX_NUMBER_OF_WAGONS) {
int type = wagonTypesJList.getSelectedIndex();
wagons.add(new Integer(type));
updateMaxWagonsText();
this.repaint();
}
}
Outgoing Methods (calls):
jfreerails.client.view.SelectWagonsJPanel.getWagons
Javadoc:
No Javadoc available
Method code:
public int[] getWagons() {
int[] wagonsArray = new int[wagons.size()];
for (int i = 0; i < wagons.size(); i++) {
Integer type = wagons.get(i);
wagonsArray[i] = type.intValue();
}
return wagonsArray;
}
No outgoing methods.
jfreerails.client.view.SelectWagonsJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the FormEditor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
wagonTypesJList = new javax.swing.JList();
okjButton = new javax.swing.JButton();
clearjButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
setBackground(new java.awt.Color(0, 255, 51));
setMinimumSize(new java.awt.Dimension(640, 400));
setPreferredSize(new java.awt.Dimension(620, 380));
jPanel1.setLayout(new java.awt.GridBagLayout());
jPanel1.setMinimumSize(new java.awt.Dimension(170, 300));
jPanel1.setPreferredSize(new java.awt.Dimension(170, 300));
wagonTypesJList.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyTyped(java.awt.event.KeyEvent evt) {
wagonTypesJListKeyTyped(evt);
}
});
wagonTypesJList.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
wagonTypesJListMouseClicked(evt);
}
});
jScrollPane1.setViewportView(wagonTypesJList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel1.add(jScrollPane1, gridBagConstraints);
okjButton.setText("OK");
okjButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonAction(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
jPanel1.add(okjButton, gridBagConstraints);
clearjButton.setText("Clear");
clearjButton.setActionCommand("clear");
clearjButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel1.add(clearjButton, gridBagConstraints);
jLabel1.setFont(new java.awt.Font("Dialog", 0, 10));
jLabel1.setText("The maximum train length is 6 wagons");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 8);
jPanel1.add(jLabel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(20, 400, 70, 10);
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
add(jPanel1, gridBagConstraints);
}// GEN-END:initComponents
Outgoing Methods (calls):
jfreerails.client.view.SelectWagonsJPanel.jButton1ActionPerformed
Javadoc:
No Javadoc available
Method code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton1ActionPerformed
// Add your handling code here:
wagons.clear();
jLabel1.setText("");
this.repaint();
} // GEN-LAST:event_jButton1ActionPerformed
No outgoing methods.
jfreerails.client.view.SelectWagonsJPanel.okButtonAction
Javadoc:
No Javadoc available
Method code:
private void okButtonAction(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_okButtonAction
// Add your handling code here:
} // GEN-LAST:event_okButtonAction
No outgoing methods.
jfreerails.client.view.SelectWagonsJPanel.paint
Javadoc:
No Javadoc available
Method code:
@Override
public void paint(Graphics g) {
// paint the background
g.drawImage(this.stationView, 0, 0, null);
int x = this.getWidth();
int y = 330;
final int SCALED_IMAGE_HEIGHT = 50;
// paint the wagons
for (int i = this.wagons.size() - 1; i >= 0; i--) { // Count down so we
// paint the wagon
// at the end of the
// train first.
Integer type = wagons.get(i);
Image image = rr.getWagonImages(type.intValue()).getSideOnImage();
int scaledWidth = image.getWidth(null) * SCALED_IMAGE_HEIGHT
/ image.getHeight(null);
x -= scaledWidth;
g.drawImage(image, x, y, scaledWidth, SCALED_IMAGE_HEIGHT, null);
}
// paint the engine
if (-1 != this.engineType) { // If an engine is selected.
Image image = rr.getEngineImages(engineType).getSideOnImage();
int scaledWidth = (image.getWidth(null) * SCALED_IMAGE_HEIGHT)
/ image.getHeight(null);
x -= scaledWidth;
g.drawImage(image, x, y, scaledWidth, SCALED_IMAGE_HEIGHT, null);
}
this.paintChildren(g);
}
Outgoing Methods (calls):
jfreerails.client.view.SelectWagonsJPanel.resetSelectedWagons
Javadoc:
No Javadoc available
Method code:
public void resetSelectedWagons() {
this.wagons.clear();
}
No outgoing methods.
jfreerails.client.view.SelectWagonsJPanel.setEngineType
Javadoc:
No Javadoc available
Method code:
public void setEngineType(int engineType) {
this.engineType = engineType;
}
No outgoing methods.
jfreerails.client.view.SelectWagonsJPanel.setup
Javadoc:
/** * Initializes the UI components of the SelectWagonsJPanel by configuring * the wagon types list model, cell renderer, and OK button action listener. * * @param mr The ModelRoot instance providing access to the world data. * @param vl The RenderersRoot instance used for rendering wagon details. * @param closeAction The Action to trigger when the OK button is clicked. */
Method code:
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
World2ListModelAdapter w2lma = new World2ListModelAdapter(
mr.getWorld(), SKEY.CARGO_TYPES);
this.wagonTypesJList.setModel(w2lma);
this.rr = vl;
WagonCellRenderer wagonCellRenderer = new WagonCellRenderer(w2lma,
rr);
this.wagonTypesJList.setCellRenderer(wagonCellRenderer);
this.okjButton.addActionListener(closeAction);
}
Outgoing Methods (calls):
jfreerails.client.view.SelectWagonsJPanel.updateMaxWagonsText
Javadoc:
No Javadoc available
Method code:
private void updateMaxWagonsText() {
if (wagons.size() >= TrainModel.MAX_NUMBER_OF_WAGONS) {
jLabel1.setText("Max train length is "
+ TrainModel.MAX_NUMBER_OF_WAGONS + " wagons");
} else {
jLabel1.setText("");
}
}
No outgoing methods.
jfreerails.client.view.SelectWagonsJPanel.wagonTypesJListKeyTyped
Javadoc:
No Javadoc available
Method code:
private void wagonTypesJListKeyTyped(java.awt.event.KeyEvent evt) { // GEN-FIRST:event_wagonTypesJListKeyTyped
// Add your handling code here:
if (KeyEvent.VK_ENTER == evt.getKeyCode()) {
addwagon();
} else {
}
} // GEN-LAST:event_wagonTypesJListKeyTyped
Outgoing Methods (calls):
jfreerails.client.view.SelectWagonsJPanel.wagonTypesJListMouseClicked
Javadoc:
No Javadoc available
Method code:
private void wagonTypesJListMouseClicked(java.awt.event.MouseEvent evt) { // GEN-FIRST:event_wagonTypesJListMouseClicked
// Add your handling code here:
addwagon();
} // GEN-LAST:event_wagonTypesJListMouseClicked
Outgoing Methods (calls):
jfreerails.client.view.ServerControlModel.getGameSpeedDesc
Javadoc:
/** * Returns human readable string description of <code>tickPerSecond</code> * number. Looks for <code>tickPerSecond</code> in * <code>targetTicksPerSecondActions</code>. If appropriate action is not * found returns first greater value or the greatest value. * * @param tickPerSecond * int * @return String human readable description */
Method code:
/**
* Returns human readable string description of <code>tickPerSecond</code>
* number. Looks for <code>tickPerSecond</code> in
* <code>targetTicksPerSecondActions</code>. If appropriate action is not
* found returns first greater value or the greatest value.
*
* @param tickPerSecond
* int
* @return String human readable description
*/
public String getGameSpeedDesc(int tickPerSecond) {
SetTargetTicksPerSecondAction action = null;
for (int i = 0; i < speedActions.length; i++) {
action = speedActions[i];
if (action.speed >= tickPerSecond)
break;
}
return (String) action.getValue(Action.NAME);
}
No outgoing methods.
jfreerails.client.view.ServerControlModel.getLoadGameAction
Javadoc:
/** * @return an action to load a game. */
Method code:
/**
* @return an action to load a game.
*/
public Action getLoadGameAction() {
return loadGameAction;
}
No outgoing methods.
jfreerails.client.view.ServerControlModel.getMapNames
Javadoc:
/** * @return an ActionAdapter representing a list of actions representing * valid map names. */
Method code:
/**
* @return an ActionAdapter representing a list of actions representing
* valid map names.
*/
public ActionAdapter getMapNames() {
return selectMapActions;
}
No outgoing methods.
jfreerails.client.view.ServerControlModel.getNewGameAction
Javadoc:
/** * When calling this action, set the action command string to the desired * map name, or call the appropriate selectMapAction. * * @return an action to start a new game */
Method code:
/**
* When calling this action, set the action command string to the desired
* map name, or call the appropriate selectMapAction.
*
* @return an action to start a new game
*/
public Action getNewGameAction() {
return newGameAction;
}
No outgoing methods.
jfreerails.client.view.ServerControlModel.getSaveGameAction
Javadoc:
/** * @return an action to save a game TODO The action produces a file selector * dialog to save the game */
Method code:
/**
* @return an action to save a game TODO The action produces a file selector
* dialog to save the game
*/
public Action getSaveGameAction() {
return saveGameAction;
}
No outgoing methods.
jfreerails.client.view.ServerControlModel.getSetTargetTickPerSecondActions
Javadoc:
/** * @return an action adapter to set the target ticks per second */
Method code:
/**
* @return an action adapter to set the target ticks per second
*/
public ActionAdapter getSetTargetTickPerSecondActions() {
return targetTicksPerSecondActions;
}
No outgoing methods.
jfreerails.client.view.ServerControlModel.getTargetTicksPerSecond
Javadoc:
No Javadoc available
Method code:
public int getTargetTicksPerSecond() {
ReadOnlyWorld world = modelRoot.getWorld();
return ((GameSpeed) world.get(ITEM.GAME_SPEED)).getSpeed();
}
Outgoing Methods (calls):
jfreerails.client.view.ServerControlModel.propertyChange
Javadoc:
No Javadoc available
Method code:
public void propertyChange(Property p, Object oldValue, Object newValue) {
// switch (p) {
// case SAVED_GAMES_LIST:
// updateLoadGameAction();
// break;
//
// default:
// break;
// }
}
No outgoing methods.
jfreerails.client.view.ServerControlModel.setServerControlInterface
Javadoc:
No Javadoc available
Method code:
public void setServerControlInterface() {
// Check that there is a file to load..
saveGameAction.setEnabled(true);
Enumeration<Action> e = targetTicksPerSecondActions.getActions();
targetTicksPerSecondActions.setPerformActionOnSetSelectedItem(false);
while (e.hasMoreElements()) {
e.nextElement().setEnabled(true);
}
String[] mapNames = NewGameMessage2Server.getMapNames();
Action[] actions = new Action[mapNames.length];
for (int j = 0; j < actions.length; j++) {
actions[j] = new NewGameAction(mapNames[j]);
actions[j].setEnabled(true);
}
selectMapActions = new ActionAdapter(actions);
newGameAction.setEnabled(true);
}
Outgoing Methods (calls):
jfreerails.client.view.ServerControlModel.setup
Javadoc:
/** * Initializes the instance by setting the root model and dialogue box controller, * then registers this object as a property change listener for the model root. * * @param modelRoot The root model to which the listener is added. * @param dbc The controller responsible for managing dialogue box interactions. */
Method code:
public void setup(ModelRootImpl modelRoot, DialogueBoxController dbc) {
this.modelRoot = modelRoot;
this.dbc = dbc;
modelRoot.addPropertyChangeListener(this);
}
Outgoing Methods (calls):
jfreerails.client.view.SetTargetTicksPerSecondAction.actionPerformed
Javadoc:
No Javadoc available
Method code:
public void actionPerformed(ActionEvent e) {
int speed2set = speed;
if (speed == 0) { // pausing/unpausing
speed2set = -1 * getTargetTicksPerSecond();
}
modelRoot.doMove(ChangeGameSpeedMove.getMove(modelRoot.getWorld(),
new GameSpeed(speed2set)));
}
Outgoing Methods (calls):
jfreerails.client.view.ShowJavaProperties.getPropertiesHtmlString
Javadoc:
No Javadoc available
Method code:
public static String getPropertiesHtmlString() {
Properties p = System.getProperties();
StringBuffer sb = new StringBuffer();
/* We set the width of the table so that its text word-wraps. */
sb.append("<html><h3>Java System Properties</h3><table width =\""
+ TABLE_WIDTH + "\" align = \"left\" valign = \"top\">\n");
Enumeration keys = p.keys();
//We use an ArrayList so that the keys can be sorted into alphabetical order
ArrayList<String> list = new ArrayList<String>();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
list.add(key);
}
Collections.sort(list);
for(String key : list){
String value = p.getProperty(key);
/*
* Insert a line break after each ";". This makes reading classpath
* elements easier.
*/
value = value.replaceAll(";", ";<br>");
sb
.append("<tr><td>" + key + " </td><td> " + value
+ "</td></tr>\n");
}
sb.append("</table></html>\n");
return sb.toString();
}
No outgoing methods.
jfreerails.client.view.ShowJavaProperties.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
logger.info(getPropertiesHtmlString());
}
Outgoing Methods (calls):
jfreerails.client.view.StationBuildAction.actionPerformed
Javadoc:
No Javadoc available
Method code:
public void actionPerformed(ActionEvent e) {
Point value = (Point) stationBuildAction
.getValue(StationBuildAction.STATION_POSITION_KEY);
MoveStatus ms = stationBuilder.buildStation(new ImPoint(value.x,
value.y));
String message = null;
if (ms.isOk()) {
stationBuildAction.setEnabled(false);
} else {
message = ms.message;
}
modelRoot.setProperty(ModelRoot.Property.CURSOR_MESSAGE, message);
}
Outgoing Methods (calls):
jfreerails.client.view.StationBuildModel.canBuildStationHere
Javadoc:
No Javadoc available
Method code:
public boolean canBuildStationHere() {
Point p = (Point) stationBuildAction
.getValue(StationBuildAction.STATION_POSITION_KEY);
return stationBuilder.tryBuildingStation(new ImPoint(p.x, p.y)).ok;
}
Outgoing Methods (calls):
jfreerails.client.view.StationBuildModel.getStationBuildAction
Javadoc:
No Javadoc available
Method code:
public StationBuildAction getStationBuildAction() {
return stationBuildAction;
}
No outgoing methods.
jfreerails.client.view.StationBuildModel.getStationCancelAction
Javadoc:
No Javadoc available
Method code:
public Action getStationCancelAction() {
return stationCancelAction;
}
No outgoing methods.
jfreerails.client.view.StationBuildModel.getStationChooseAction
Javadoc:
No Javadoc available
Method code:
public Action getStationChooseAction(Integer ruleID) {
return id2Action.get(ruleID);
}
No outgoing methods.
jfreerails.client.view.StationBuildModel.getStationChooseActions
Javadoc:
No Javadoc available
Method code:
public Action[] getStationChooseActions() {
return stationChooseActions.toArray(new Action[stationChooseActions.size()]);
}
No outgoing methods.
jfreerails.client.view.StationBuildModel.isPositionFollowsMouse
Javadoc:
No Javadoc available
Method code:
public boolean isPositionFollowsMouse() {
return positionFollowsMouse;
}
No outgoing methods.
jfreerails.client.view.StationBuildModel.setPositionFollowsMouse
Javadoc:
No Javadoc available
Method code:
public void setPositionFollowsMouse(boolean positionFollowsMouse) {
this.positionFollowsMouse = positionFollowsMouse;
}
No outgoing methods.
jfreerails.client.view.StationCancelAction.actionPerformed
Javadoc:
No Javadoc available
Method code:
public void actionPerformed(ActionEvent e) {
stationBuildAction.setEnabled(false);
}
No outgoing methods.
jfreerails.client.view.StationChooseAction.actionPerformed
Javadoc:
No Javadoc available
Method code:
public void actionPerformed(ActionEvent e) {
stationBuilder.setStationType(actionId);
TrackRule trackRule = (TrackRule) modelRoot.getWorld().get(
SKEY.TRACK_RULES, actionId);
// Show the relevant station radius when the station type's menu
// item
// gets focus.
stationBuildAction.putValue(StationBuildAction.STATION_RADIUS_KEY,
new Integer(trackRule.getStationRadius()));
stationBuildAction.setEnabled(true);
}
Outgoing Methods (calls):
jfreerails.client.view.StationInfoJPanel.display
Javadoc:
No Javadoc available
Method code:
private void display() {
if (wi.getRowID() > 0) {
this.previousStation.setEnabled(true);
} else {
this.previousStation.setEnabled(false);
}
if (wi.getRowID() < (wi.size() - 1)) {
this.nextStation.setEnabled(true);
} else {
this.nextStation.setEnabled(false);
}
int stationNumber = wi.getIndex();
String label;
if (stationNumber != WorldIterator.BEFORE_FIRST) {
StationModel station = (StationModel) w.get(modelRoot.getPrincipal(),
KEY.STATIONS, stationNumber);
FreerailsTile tile = (FreerailsTile) w
.getTile(station.x, station.y);
String stationTypeName = tile.getTrackPiece().getTrackRule().getTypeName();
cargoBundleIndex = station.getCargoBundleID();
ImmutableCargoBundle cargoWaiting = (ImmutableCargoBundle) w.get(
modelRoot
.getPrincipal(), KEY.CARGO_BUNDLES, station.getCargoBundleID());
String title = "<h2 align=\"center\">" + station.getStationName()
+ " (" + stationTypeName + ")</h2>";
String table = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"3\"><tr><td>&nbsp;</td>\n <td>Will pay for</td>\n <td>Supplies / cars per year</td><td>Waiting for pickup / car loads</td> </tr>";
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
// get the values
CargoType cargoType = (CargoType) w.get(SKEY.CARGO_TYPES, i);
String demanded = (station.getDemand().isCargoDemanded(i) ? "Yes"
: "No");
int amountSupplied = station.getSupply().getSupply(i);
String supply = (amountSupplied > 0) ? String
.valueOf(amountSupplied
/ WagonType.UNITS_OF_CARGO_PER_WAGON)
: "&nbsp;";
int amountWaiting = cargoWaiting.getAmount(i);
String waiting = (amountWaiting > 0) ? String
.valueOf(amountWaiting
/ WagonType.UNITS_OF_CARGO_PER_WAGON)
: "&nbsp;";
// build the html
table += "<tr>";
table += "<td>" + cargoType.getDisplayName() + "</td>";
table += "<td>" + demanded + "</td>";
table += "<td>" + supply + "</td>";
table += "<td>" + waiting + "</td>";
table += "</tr>";
}
table += "</table>";
label = "<html>" + title + table + "</html>";
} else {
cargoBundleIndex = WorldIterator.BEFORE_FIRST;
label = "<html><h2 align=\"center\">No Station "
+ "Selected</h2></html>";
}
jLabel1.setText(label);
this.repaint();
}
Outgoing Methods (calls):
jfreerails.client.view.StationInfoJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jLabel1 = new javax.swing.JLabel();
nextStation = new javax.swing.JButton();
previousStation = new javax.swing.JButton();
close = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
setMinimumSize(new java.awt.Dimension(250, 177));
jLabel1.setFont(new java.awt.Font("Dialog", 0, 10));
jLabel1
.setText("<html>\n<h4 align=\"center\">Supply and Demand at stationName</h4>\n<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"2\">\n <tr>\n <td>&nbsp;</td>\n <td>Will pay<br>for</td>\n <td>Supplies<br>(cars per year)</td>\n <td>Waiting for pickup<br>(car loads)</td>\n </tr>\n <tr>\n <td>Mail</td>\n <td>Yes</td>\n <td>&nbsp;</td>\n <td>&nbsp;</td>\n </tr>\n <tr>\n <td>Passengers</td>\n <td>No</td>\n <td>3</td>\n <td>2.5</td>\n </tr>\n \n</table>\n\n</html>");
jLabel1.setVerticalAlignment(javax.swing.SwingConstants.TOP);
jLabel1.setAlignmentY(0.0F);
jLabel1.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 4, 8);
add(jLabel1, gridBagConstraints);
nextStation.setText("next ->");
nextStation.setMargin(new java.awt.Insets(0, 0, 0, 0));
nextStation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextStationActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(nextStation, gridBagConstraints);
previousStation.setText("<- previous");
previousStation.setMargin(new java.awt.Insets(0, 0, 0, 0));
previousStation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
previousStationActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(previousStation, gridBagConstraints);
close.setText("close");
close.setMargin(new java.awt.Insets(0, 0, 0, 0));
close.setMaximumSize(new java.awt.Dimension(65, 22));
close.setMinimumSize(new java.awt.Dimension(65, 22));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(close, gridBagConstraints);
}// GEN-END:initComponents
Outgoing Methods (calls):
jfreerails.client.view.StationInfoJPanel.itemAdded
Javadoc:
No Javadoc available
Method code:
public void itemAdded(KEY key, int index, FreerailsPrincipal principal) {
if (modelRoot.getPrincipal().equals(principal))
reactToUpdate(key, index, true);
}
Outgoing Methods (calls):
jfreerails.client.view.StationInfoJPanel.itemRemoved
Javadoc:
No Javadoc available
Method code:
public void itemRemoved(KEY key, int index, FreerailsPrincipal principal) {
if (modelRoot.getPrincipal().equals(principal))
reactToUpdate(key, index, false);
}
Outgoing Methods (calls):
jfreerails.client.view.StationInfoJPanel.listUpdated
Javadoc:
No Javadoc available
Method code:
public void listUpdated(KEY key, int index, FreerailsPrincipal principal) {
if (modelRoot.getPrincipal().equals(principal))
reactToUpdate(key, index, false);
}
Outgoing Methods (calls):
jfreerails.client.view.StationInfoJPanel.nextStationActionPerformed
Javadoc:
No Javadoc available
Method code:
private void nextStationActionPerformed(java.awt.event.ActionEvent evt) {
// GEN-FIRST:event_nextStationActionPerformed
// Add your handling code here:
if (wi.next()) {
ImPoint p = new ImPoint(((StationModel) wi.getElement())
.getStationX(), ((StationModel) wi.getElement())
.getStationY());
this.modelRoot.setProperty(ModelRoot.Property.CURSOR_POSITION, p);
display();
} else {
throw new IllegalStateException();
}
} // GEN-LAST:event_nextStationActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.StationInfoJPanel.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(Graphics g) {
/* We need to update if the cargo bundle has changed. */
FreerailsPrincipal playerPrincipal = this.modelRoot.getPrincipal();
/*
* Avoid a array out of bounds exception when there are no stations and
* the stations tab is visible.
*/
if (w.boundsContain(playerPrincipal, KEY.CARGO_BUNDLES,
cargoBundleIndex)) {
FreerailsSerializable currentCargoBundle = w.get(playerPrincipal,
KEY.CARGO_BUNDLES, this.cargoBundleIndex);
if (lastCargoBundle != currentCargoBundle) {
this.display();
lastCargoBundle = currentCargoBundle;
}
}
super.paintComponent(g);
}
Outgoing Methods (calls):
jfreerails.client.view.StationInfoJPanel.previousStationActionPerformed
Javadoc:
No Javadoc available
Method code:
private void previousStationActionPerformed(java.awt.event.ActionEvent evt) {
// GEN-FIRST:event_previousStationActionPerformed
// Add your handling code here:
if (wi.previous()) {
ImPoint p = new ImPoint(((StationModel) wi.getElement())
.getStationX(), ((StationModel) wi.getElement())
.getStationY());
this.modelRoot.setProperty(ModelRoot.Property.CURSOR_POSITION, p);
display();
} else {
throw new IllegalStateException();
}
} // GEN-LAST:event_previousStationActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.StationInfoJPanel.reactToUpdate
Javadoc:
No Javadoc available
Method code:
private void reactToUpdate(KEY key, int changedIndex, boolean isAddition) {
if (!isVisible()) {
return;
}
int currentIndex = wi.getIndex();
if (key == KEY.CARGO_BUNDLES) {
if (changedIndex == cargoBundleIndex) {
/* update our cargo bundle */
display();
return;
}
} else if (key == KEY.STATIONS) {
wi.reset();
if (currentIndex != WorldIterator.BEFORE_FIRST) {
if (currentIndex < wi.size()) {
wi.gotoIndex(currentIndex);
} else {
currentIndex = WorldIterator.BEFORE_FIRST;
}
}
if (isAddition && wi.getIndex() == WorldIterator.BEFORE_FIRST) {
if (wi.next()) {
display();
}
}
if (currentIndex == changedIndex
|| currentIndex == WorldIterator.BEFORE_FIRST) {
display();
}
}
return;
}
Outgoing Methods (calls):
jfreerails.client.view.StationInfoJPanel.removeCloseButton
Javadoc:
No Javadoc available
Method code:
void removeCloseButton() {
this.remove(close);
}
No outgoing methods.
jfreerails.client.view.StationInfoJPanel.setStation
Javadoc:
No Javadoc available
Method code:
public void setStation(int stationNumber) {
this.wi.gotoIndex(stationNumber);
display();
}
Outgoing Methods (calls):
jfreerails.client.view.StationInfoJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot mr, RenderersRoot vl, Action al) {
this.wi = new NonNullElements(KEY.STATIONS, mr.getWorld(), mr
.getPrincipal());
addComponentListener(componentListener);
this.w = mr.getWorld();
this.modelRoot = mr;
this.close.addActionListener(al);
}
Outgoing Methods (calls):
jfreerails.client.view.StationPlacementCursor.init
Javadoc:
No Javadoc available
Method code:
private void init() {
if (buildEnabled) {
mapView.addMouseListener(this);
mapView.addMouseMotionListener(this);
stationRadiusRenderer.show();
} else {
stationRadiusRenderer.hide();
mapView.removeMouseListener(this);
mapView.removeMouseMotionListener(this);
}
stationBuildModel.getStationBuildAction().addPropertyChangeListener(
buildActionListener);
}
Outgoing Methods (calls):
jfreerails.client.view.StationPlacementCursor.mouseClicked
Javadoc:
No Javadoc available
Method code:
@Override
public void mouseClicked(MouseEvent e) {
int button = e.getButton();
if (button == MouseEvent.BUTTON1) {
/* attempt to build */
stationBuildModel.getStationBuildAction().actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
} else if (button == MouseEvent.BUTTON3) {
/* cancel the build */
stationBuildModel.getStationCancelAction().actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
}
}
Outgoing Methods (calls):
jfreerails.client.view.StationPlacementCursor.mouseEntered
Javadoc:
No Javadoc available
Method code:
@Override
public void mouseEntered(MouseEvent e) {
stationRadiusRenderer.show();
}
Outgoing Methods (calls):
jfreerails.client.view.StationPlacementCursor.mouseExited
Javadoc:
No Javadoc available
Method code:
@Override
public void mouseExited(MouseEvent e) {
stationRadiusRenderer.hide();
}
Outgoing Methods (calls):
jfreerails.client.view.StationPlacementCursor.mouseMoved
Javadoc:
No Javadoc available
Method code:
@Override
public void mouseMoved(MouseEvent e) {
if (stationBuildModel.isPositionFollowsMouse()) {
Point p = e.getPoint();
Point mapCoord = new Point((int) (p.x / scale), (int) (p.y / scale));
stationBuildModel.getStationBuildAction().putValue(
StationBuildModel.StationBuildAction.STATION_POSITION_KEY,
mapCoord);
}
}
Outgoing Methods (calls):
jfreerails.client.view.StationPlacementCursor.wireUp
Javadoc:
No Javadoc available
Method code:
public static void wireUp(ActionRoot actionRoot, StationRadiusRenderer srr,
MapViewJComponent mapView) {
StationPlacementCursor spc = new StationPlacementCursor(actionRoot,
srr, mapView);
spc.init();
}
Outgoing Methods (calls):
jfreerails.client.view.TerrainInfoJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
terrainImage = new javax.swing.JLabel();
terrainName = new javax.swing.JLabel();
terrainDescription = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
terrainImage.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/jfreerails/client/graphics/terrain/City_0.png")));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(8, 8, 4, 4);
add(terrainImage, gridBagConstraints);
terrainName.setFont(new java.awt.Font("Dialog", 1, 14));
terrainName.setText("City");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 8);
add(terrainName, gridBagConstraints);
terrainDescription.setFont(new java.awt.Font("Dialog", 0, 12));
terrainDescription
.setText("<html>\n<p>Right-of-Way costs X per mile. </p>\n<table width=\"75%\" >\n <tr> \n <td><strong>Supplies:</strong></td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td>Mail </td>\n <td>2</td>\n </tr>\n <tr> \n <td>Passengers</td>\n <td>2</td>\n </tr>\n <tr> \n <td> <strong>Demands</strong></td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td>Mail</td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td>Passengers</td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td><strong>Converts</strong></td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td>Livestock to Food</td>\n <td>&nbsp;</td>\n </tr>\n <tr>\n <td>Steel to Goods</td>\n <td>&nbsp;</td>\n </tr>\n</table>\n</html>");
terrainDescription.setVerticalAlignment(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 8, 4, 8);
add(terrainDescription, gridBagConstraints);
}// GEN-END:initComponents
No outgoing methods.
jfreerails.client.view.TerrainInfoJPanel.setTerrainType
Javadoc:
No Javadoc available
Method code:
public void setTerrainType(int typeNumber) {
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES, typeNumber);
String row = "<p>Right-of-Way costs $" + type.getRightOfWay()
+ " per mile. </p>";
String tableString = "";
int cargosProduced = type.getProduction().size();
int cargosConsumed = type.getConsumption().size();
int cargosConverted = type.getConversion().size();
if ((cargosProduced + cargosConsumed + cargosConverted) > 0) {
// if the terrain type produces, consumes, or converts anything.
tableString = "<table width=\"75%\" >";
if (cargosProduced != 0) {
tableString += "<tr> <td><strong>Supplies</strong></td> <td>&nbsp;</td> </tr>";
for (int i = 0; i < cargosProduced; i++) {
Production p = type.getProduction().get(i);
CargoType c = (CargoType) w.get(SKEY.CARGO_TYPES, p
.getCargoType());
String supply = String.valueOf(p.getRate()
/ WagonType.UNITS_OF_CARGO_PER_WAGON);
tableString += "<tr> <td>" + c.getDisplayName()
+ " </td><td>" + supply + "</td></tr>";
}
}
if (cargosConsumed != 0) {
tableString += "<tr> <td><strong>Demands</strong></td> <td>&nbsp;</td> </tr>";
for (int i = 0; i < cargosConsumed; i++) {
Consumption p = type.getConsumption().get(i);
CargoType c = (CargoType) w.get(SKEY.CARGO_TYPES, p
.getCargoType());
tableString += "<tr> <td>" + c.getDisplayName()
+ " </td><td>&nbsp;</td></tr>";
}
}
if (cargosConverted != 0) {
tableString += "<tr> <td><strong>Converts</strong></td> <td>&nbsp;</td> </tr>";
for (int i = 0; i < cargosConverted; i++) {
Conversion p = type.getConversion().get(i);
CargoType input = (CargoType) w.get(SKEY.CARGO_TYPES, p
.getInput());
CargoType output = (CargoType) w.get(SKEY.CARGO_TYPES, p
.getOutput());
tableString += "<tr> <td colspan=\"2\">"
+ input.getDisplayName() + " to "
+ output.getDisplayName() + "</td></tr>";
}
}
tableString += "</table> ";
}
String labelString = "<html>" + row + tableString + "</html>";
terrainDescription.setText(labelString);
terrainName.setText(type.getDisplayName());
Image tileIcon = rr.getTileViewWithNumber(typeNumber)
.getDefaultIcon();
terrainImage.setIcon(new ImageIcon(tileIcon));
repaint();
}
Outgoing Methods (calls):
jfreerails.client.view.TerrainInfoJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ReadOnlyWorld w, RenderersRoot vl) {
this.w = w;
this.rr = vl;
}
No outgoing methods.
jfreerails.client.view.TrainCellRenderer.getListCellRendererComponent
Javadoc:
No Javadoc available
Method code:
public Component getListCellRendererComponent(JList list, Object value,
/* value to display */
int index, /* cell index */
boolean isSelected, /* is the cell selected */
boolean cellHasFocus) /* the list and the cell have the focus */{
EngineType engine = (EngineType) value;
label.setFont(new java.awt.Font("Dialog", 0, 12));
String text = "<html><body>" + (isSelected ? "<strong>" : "")
+ engine.getEngineTypeName() + "<br>"
+ engine.getMaxSpeed() + " m.p.h. "
+ engine.getPowerAtDrawbar() + " hp $"
+ engine.getPrice().toString()
+ (isSelected ? "</strong>" : "") + "</body></html>";
label.setText(text);
Image image = rr.getEngineImages(index).getSideOnImage();
int height = image.getHeight(null);
int width = image.getWidth(null);
int scale = height / 50;
ImageIcon icon = new ImageIcon(image.getScaledInstance(width
/ scale, height / scale, Image.SCALE_FAST));
label.setIcon(icon);
return label;
}
Outgoing Methods (calls):
jfreerails.client.view.TrainDescriptionJPanel.displayTrain
Javadoc:
No Javadoc available
Method code:
public void displayTrain(int newTrainNumber) {
NonNullElements it = new NonNullElements(KEY.TRAINS, w, principal);
it.gotoIndex(newTrainNumber);
this.trainNumber = newTrainNumber;
trainViewJPanel1.display(newTrainNumber);
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
newTrainNumber);
for (int i = 0; i < train.getNumberOfWagons(); i++) {
// this.sideOnTrainViewJPanel1.addWagon(train.getWagon(i));
}
int cargoBundleID = train.getCargoBundleID();
ImmutableCargoBundle cb = (ImmutableCargoBundle) w.get(
principal, KEY.CARGO_BUNDLES, cargoBundleID);
String s = "Train #" + it.getNaturalNumber() + ": ";
int numberOfTypesInBundle = 0;
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
int amount = cb.getAmount(i);
if (0 != amount) {
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, i);
String cargoTypeName = ct.getDisplayName();
if (0 != numberOfTypesInBundle) {
s += "; ";
}
numberOfTypesInBundle++;
s += cargoTypeName + " (" + amount + ")";
}
}
if (0 == numberOfTypesInBundle) {
s += "no cargo";
}
s += ".";
this.jLabel1.setText(s);
this.lastCargoBundle = cb;
this.lastTrain = train;
}
Outgoing Methods (calls):
jfreerails.client.view.TrainDescriptionJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jLabel1 = new javax.swing.JLabel();
trainViewJPanel1 = new jfreerails.client.view.TrainListCellRenderer();
setLayout(new java.awt.GridBagLayout());
setBorder(new javax.swing.border.TitledBorder("Current Details"));
setPreferredSize(new java.awt.Dimension(250, 97));
jLabel1.setFont(new java.awt.Font("Dialog", 0, 12));
jLabel1
.setText("<html><head></head><body>Trains X: 20 passengers, 15 tons of mfg goods, 12 sacks of mail, and 7 tons of livestock.</body></html>");
jLabel1.setMinimumSize(new java.awt.Dimension(250, 17));
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
jLabel1.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jLabel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
add(trainViewJPanel1, gridBagConstraints);
}// GEN-END:initComponents
No outgoing methods.
jfreerails.client.view.TrainDescriptionJPanel.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(Graphics arg0) {
//Check whether the train or its cargo have changed since the last call to this method.
updateIfNecessary();
super.paintComponent(arg0);
}
Outgoing Methods (calls):
jfreerails.client.view.TrainDescriptionJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
this.trainViewJPanel1.setup(mr, vl, closeAction);
trainViewJPanel1.setHeight(30);
trainViewJPanel1.setCenterTrain(true);
this.w = mr.getWorld();
principal = mr.getPrincipal();
}
Outgoing Methods (calls):
jfreerails.client.view.TrainDescriptionJPanel.updateIfNecessary
Javadoc:
No Javadoc available
Method code:
private void updateIfNecessary() {
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
trainNumber);
for (int i = 0; i < train.getNumberOfWagons(); i++) {
// this.sideOnTrainViewJPanel1.addWagon(train.getWagon(i));
}
int cargoBundleID = train.getCargoBundleID();
FreerailsSerializable cb = w.get(
principal, KEY.CARGO_BUNDLES, cargoBundleID);
if(train != lastTrain || cb != lastCargoBundle)
displayTrain(trainNumber);
}
Outgoing Methods (calls):
jfreerails.client.view.TrainDialogueJPanel.display
Javadoc:
No Javadoc available
Method code:
public void display(int trainNumber) {
wi = new NonNullElements(KEY.TRAINS, w, principal);
wi.gotoIndex(trainNumber);
if (wi.getRowID() > 0) {
this.previousJButton.setEnabled(true);
} else {
this.previousJButton.setEnabled(false);
}
if (wi.getRowID() < (wi.size() - 1)) {
this.nextJButton.setEnabled(true);
} else {
this.nextJButton.setEnabled(false);
}
newTrainScheduleJPanel1.display(trainNumber);
trainDetailsJPanel1.displayTrain(trainNumber);
}
Outgoing Methods (calls):
jfreerails.client.view.TrainDialogueJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
newTrainScheduleJPanel1 = new jfreerails.client.view.TrainScheduleJPanel();
trainDetailsJPanel1 = new TrainDescriptionJPanel();
previousJButton = new javax.swing.JButton();
nextJButton = new javax.swing.JButton();
trainListJButton = new javax.swing.JButton();
closeJButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(510, 400));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(newTrainScheduleJPanel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
add(trainDetailsJPanel1, gridBagConstraints);
previousJButton.setText("last");
previousJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
previousJButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(previousJButton, gridBagConstraints);
nextJButton.setText("next");
nextJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextJButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(nextJButton, gridBagConstraints);
trainListJButton.setText("Train list");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(trainListJButton, gridBagConstraints);
closeJButton.setText("Close");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(closeJButton, gridBagConstraints);
}// GEN-END:initComponents
Outgoing Methods (calls):
jfreerails.client.view.TrainDialogueJPanel.itemAdded
Javadoc:
No Javadoc available
Method code:
public void itemAdded(KEY key, int index, FreerailsPrincipal p) {
}
No outgoing methods.
jfreerails.client.view.TrainDialogueJPanel.itemRemoved
Javadoc:
No Javadoc available
Method code:
public void itemRemoved(KEY key, int index, FreerailsPrincipal p) {
}
No outgoing methods.
jfreerails.client.view.TrainDialogueJPanel.listUpdated
Javadoc:
No Javadoc available
Method code:
public void listUpdated(KEY key, int index, FreerailsPrincipal p) {
newTrainScheduleJPanel1.listUpdated(key, index, p);
}
Outgoing Methods (calls):
jfreerails.client.view.TrainDialogueJPanel.nextJButtonActionPerformed
Javadoc:
No Javadoc available
Method code:
private void nextJButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_nextJButtonActionPerformed
// Add your handling code here:
if (wi.next()) {
display(wi.getIndex());
} else {
logger.warning("Couldn't get next");
}
}// GEN-LAST:event_nextJButtonActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.TrainDialogueJPanel.previousJButtonActionPerformed
Javadoc:
No Javadoc available
Method code:
private void previousJButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_previousJButtonActionPerformed
// Add your handling code here:
if (wi.previous()) {
display(wi.getIndex());
} else {
logger.warning("Couldn't get previous");
}
}// GEN-LAST:event_previousJButtonActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.TrainDialogueJPanel.setCancelButtonActionListener
Javadoc:
/** * Removes any existing ActionListener listeners from the cancel button, * then adds the specified one. */
Method code:
/**
* Removes any existing ActionListener listeners from the cancel button,
* then adds the specified one.
*/
void setCancelButtonActionListener(ActionListener l) {
ActionListener[] oldListeners = closeJButton.getActionListeners();
for (int i = 0; i < oldListeners.length; i++) {
closeJButton.removeActionListener(oldListeners[i]);
}
this.closeJButton.addActionListener(l);
}
No outgoing methods.
jfreerails.client.view.TrainDialogueJPanel.setTrainDetailsButtonActionListener
Javadoc:
No Javadoc available
Method code:
void setTrainDetailsButtonActionListener(ActionListener l) {
ActionListener[] oldListeners = trainListJButton.getActionListeners();
for (int i = 0; i < oldListeners.length; i++) {
trainListJButton.removeActionListener(oldListeners[i]);
}
this.trainListJButton.addActionListener(l);
}
No outgoing methods.
jfreerails.client.view.TrainDialogueJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot mr, RenderersRoot vl, Action al) {
newTrainScheduleJPanel1.setup(mr, vl, al);
trainDetailsJPanel1.setup(mr, vl, al);
this.setCancelButtonActionListener(al);
this.principal = mr.getPrincipal();
this.w = mr.getWorld();
}
Outgoing Methods (calls):
jfreerails.client.view.TrainListCellRenderer.display
Javadoc:
No Javadoc available
Method code:
public void display(int newTrainNumber) {
showingOrder = false;
this.trainNumber = newTrainNumber;
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS, trainNumber);
display(train.getEngineType(), train.getConsist());
resetPreferredSize();
}
Outgoing Methods (calls):
jfreerails.client.view.TrainListCellRenderer.getHeight
Javadoc:
No Javadoc available
Method code:
@Override
public int getHeight() {
return height;
}
No outgoing methods.
jfreerails.client.view.TrainListCellRenderer.getListCellRendererComponent
Javadoc:
No Javadoc available
Method code:
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
int trainID = NonNullElements.row2index(w, KEY.TRAINS, principal, index);
display(trainID);
selected = isSelected;
if (selected) {
if (list.isFocusOwner()) {
setBackground(selectedColor);
} else {
setBackground(selectedColorNotFocused);
}
} else {
setBackground(backgroundColor);
}
return this;
}
Outgoing Methods (calls):
jfreerails.client.view.TrainListCellRenderer.itemAdded
Javadoc:
No Javadoc available
Method code:
public void itemAdded(KEY key, int index, FreerailsPrincipal p) {
}
No outgoing methods.
jfreerails.client.view.TrainListCellRenderer.itemRemoved
Javadoc:
No Javadoc available
Method code:
public void itemRemoved(KEY key, int index, FreerailsPrincipal p) {
}
No outgoing methods.
jfreerails.client.view.TrainListCellRenderer.listUpdated
Javadoc:
No Javadoc available
Method code:
public void listUpdated(KEY key, int index, FreerailsPrincipal p) {
if (showingOrder) {
if (KEY.TRAIN_SCHEDULES == key && this.scheduleID == index) {
this.display(this.trainNumber, this.scheduleOrderNumber);
}
} else {
if (KEY.TRAINS == key && this.trainNumber == index) {
this.display(this.trainNumber);
}
}
}
Outgoing Methods (calls):
jfreerails.client.view.TrainListCellRenderer.paintComponent
Javadoc:
No Javadoc available
Method code:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 0;
if (this.centerTrain) {
x = (this.getWidth() - this.trainWidth) / 2;
}
for (int i = 0; i < images.length; i++) {
g.drawImage(images[i], x, 0, null);
x += images[i].getWidth(null);
}
}
No outgoing methods.
jfreerails.client.view.TrainListCellRenderer.resetPreferredSize
Javadoc:
No Javadoc available
Method code:
private void resetPreferredSize() {
int width = 0;
for (int i = 0; i < images.length; i++) {
width += images[i].getWidth(null);
}
this.trainWidth = width;
this.setPreferredSize(new Dimension(width, height));
}
No outgoing methods.
jfreerails.client.view.TrainListCellRenderer.setCenterTrain
Javadoc:
No Javadoc available
Method code:
public void setCenterTrain(boolean b) {
this.centerTrain = b;
}
No outgoing methods.
jfreerails.client.view.TrainListCellRenderer.setHeight
Javadoc:
No Javadoc available
Method code:
public void setHeight(int i) {
height = i;
}
No outgoing methods.
jfreerails.client.view.TrainListCellRenderer.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot mr, RenderersRoot vl, Action closeAction) {
this.w = mr.getWorld();
this.vl = vl;
this.principal = mr.getPrincipal();
}
Outgoing Methods (calls):
jfreerails.client.view.TrainListJPanel.getSelectedTrainID
Javadoc:
No Javadoc available
Method code:
int getSelectedTrainID() {
/*
* Note, the selected index is not the train id since trains that have
* been removed are not shown on the list.
*/
int row = jList1.getSelectedIndex();
if (row == -1) {
return -1;
} else {
return NonNullElements.row2index(world, KEY.TRAINS, principal, row);
}
}
Outgoing Methods (calls):
jfreerails.client.view.TrainListJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
trainSummaryJPanel1 = new jfreerails.client.view.TrainSummaryJPanel();
closeJButton = new javax.swing.JButton();
showDetails = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
trainNumLabel = new javax.swing.JLabel();
trainHeadingLabel = new javax.swing.JLabel();
maintenanceLabel = new javax.swing.JLabel();
incomeLabel = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(510, 300));
closeJButton.setText("Close");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(closeJButton, gridBagConstraints);
showDetails.setText("Show details");
showDetails.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showDetailsActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(showDetails, gridBagConstraints);
jList1
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.setCellRenderer(trainSummaryJPanel1);
jList1.setDoubleBuffered(true);
jList1.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
jList1KeyPressed(evt);
}
});
jList1
.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(
javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jList1.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
jList1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jList1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
trainNumLabel.setText("Train Number");
trainNumLabel.setMaximumSize(new java.awt.Dimension(500, 500));
trainNumLabel.setPreferredSize(new java.awt.Dimension(100, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
add(trainNumLabel, gridBagConstraints);
trainHeadingLabel.setText("Headed For");
trainHeadingLabel.setPreferredSize(new java.awt.Dimension(100, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
add(trainHeadingLabel, gridBagConstraints);
maintenanceLabel.setText("Maintenance YTD");
maintenanceLabel.setPreferredSize(new java.awt.Dimension(100, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
add(maintenanceLabel, gridBagConstraints);
incomeLabel.setText("Income YTD");
incomeLabel.setPreferredSize(new java.awt.Dimension(100, 14));
add(incomeLabel, new java.awt.GridBagConstraints());
}// GEN-END:initComponents
Outgoing Methods (calls):
jfreerails.client.view.TrainListJPanel.jList1KeyPressed
Javadoc:
No Javadoc available
Method code:
private void jList1KeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_jList1KeyPressed
// Add your handling code here:
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
showTrainDetails.actionPerformed(null);
}
}// GEN-LAST:event_jList1KeyPressed
No outgoing methods.
jfreerails.client.view.TrainListJPanel.jList1MouseClicked
Javadoc:
No Javadoc available
Method code:
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_jList1MouseClicked
// Add your handling code here:
if (evt.getClickCount() == 2) {
showTrainDetails.actionPerformed(null);
}
}// GEN-LAST:event_jList1MouseClicked
No outgoing methods.
jfreerails.client.view.TrainListJPanel.jList1ValueChanged
Javadoc:
No Javadoc available
Method code:
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {// GEN-FIRST:event_jList1ValueChanged
// if a train is selected, enable the 'show details' button.
if (jList1.getSelectedIndex() != -1) {
this.showDetails.setEnabled(true);
} else {
this.showDetails.setEnabled(false);
}
}// GEN-LAST:event_jList1ValueChanged
No outgoing methods.
jfreerails.client.view.TrainListJPanel.paint
Javadoc:
No Javadoc available
Method code:
@Override
public void paint(Graphics g) {
if (null != world) {
NonNullElements trains = new NonNullElements(KEY.TRAINS, world,
principal);
int newNumberOfTrains = trains.size();
if (newNumberOfTrains != this.lastNumberOfTrains) {
jList1.setModel(new World2ListModelAdapter(world, KEY.TRAINS,
principal));
if (newNumberOfTrains > 0) {
jList1.setSelectedIndex(0);
}
lastNumberOfTrains = newNumberOfTrains;
}
}
super.paint(g);
}
Outgoing Methods (calls):
jfreerails.client.view.TrainListJPanel.propertyChange
Javadoc:
No Javadoc available
Method code:
@Override
public void propertyChange(ModelRoot.Property p, Object oldValue, Object newValue) {
if(ModelRoot.Property.SELECTED_TRAIN == p){
if(!newValue.equals(this.getSelectedTrainID())){
//update needed..
TrainModel train = (TrainModel) world.get(principal, KEY.TRAINS, (int) newValue);
this.jList1.setSelectedValue(train, true);
}
}
}
Outgoing Methods (calls):
jfreerails.client.view.TrainListJPanel.removeButtons
Javadoc:
/** When the train list is shown on a tab we don't want the buttons. */
Method code:
/** When the train list is shown on a tab we don't want the buttons. */
void removeButtons() {
this.removeAll();
java.awt.GridBagConstraints gridBagConstraints;
setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}
No outgoing methods.
jfreerails.client.view.TrainListJPanel.setShowTrainDetailsActionListener
Javadoc:
No Javadoc available
Method code:
void setShowTrainDetailsActionListener(ActionListener l) {
showTrainDetails = l;
}
No outgoing methods.
jfreerails.client.view.TrainListJPanel.setTrainViewHeight
Javadoc:
/** * Sets the height of the train view. * * @param trainViewHeight the new height value for the train view */
Method code:
public void setTrainViewHeight(int trainViewHeight) {
this.trainViewHeight = trainViewHeight;
}
No outgoing methods.
jfreerails.client.view.TrainListJPanel.setVisible
Javadoc:
No Javadoc available
Method code:
@Override
public void setVisible(boolean aFlag) {
if (aFlag && null != world) {
// jList1.setModel(new World2ListModelAdapter(world,
// KEY.TRAINS,principal));
}
super.setVisible(aFlag);
}
No outgoing methods.
jfreerails.client.view.TrainListJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(final ModelRoot mr, RenderersRoot vl,
Action closeAction) {
world = mr.getWorld();
trainSummaryJPanel1.setup(mr, vl, null);
if (rhsjTabPane) {
jList1.setModel(new World2ListModelAdapter(mr.getWorld(),
KEY.TRAINS, mr.getPrincipal()));
TrainListCellRenderer trainView = new TrainListCellRenderer(mr, vl);
jList1.setCellRenderer(trainView);
trainView.setHeight(trainViewHeight);
}
ActionListener[] oldListeners = closeJButton.getActionListeners();
for (int i = 0; i < oldListeners.length; i++) {
closeJButton.removeActionListener(oldListeners[i]);
}
closeJButton.addActionListener(closeAction);
ListSelectionListener[] old = jList1.getListSelectionListeners();
for(ListSelectionListener x : old){
jList1.removeListSelectionListener(x);
}
jList1.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int id = getSelectedTrainID();
mr.setProperty(ModelRoot.Property.SELECTED_TRAIN, id);
}
});
principal = mr.getPrincipal();
ModelRootImpl mri = (ModelRootImpl) mr;
mri.addPropertyChangeListener(this);
}
Outgoing Methods (calls):
jfreerails.client.view.TrainListJPanel.showDetailsActionPerformed
Javadoc:
No Javadoc available
Method code:
private void showDetailsActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showDetailsActionPerformed
showTrainDetails.actionPerformed(evt);
}// GEN-LAST:event_showDetailsActionPerformed
No outgoing methods.
jfreerails.client.view.TrainOrderJPanel.getListCellRendererComponent
Javadoc:
No Javadoc available
Method code:
public java.awt.Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus) {
TrainOrdersListModel.TrainOrdersListElement trainOrders = (TrainOrdersListModel.TrainOrdersListElement) value;
// Set station name
int stationNumber = trainOrders.order.stationId;
StationModel station = (StationModel) w.get(principal,
KEY.STATIONS, stationNumber);
String stationName = station.getStationName();
this.stationNameJLabel.setText(stationName);
// Set wait until full
String waitUntilFull = trainOrders.order.waitUntilFull ? "Wait until full"
: "";
this.ordersJLabel.setText(waitUntilFull);
// Set selected
if (isSelected) {
if (list.isFocusOwner()) {
setBackground(selectedColor);
} else {
setBackground(selectedColorNotFocused);
}
} else {
setBackground(backgroundColor);
}
// Set goto status.
switch (trainOrders.gotoStatus) {
case TrainOrdersListModel.DONT_GOTO:
this.gotoIcon.setIcon(this.dontGoto);
break;
case TrainOrdersListModel.GOTO_AFTER_PRIORITY_ORDERS:
this.gotoIcon.setIcon(this.gotoAfterPriorityOrders);
break;
case TrainOrdersListModel.GOTO_NOW:
this.gotoIcon.setIcon(this.gotoNow);
break;
default:
throw new IllegalArgumentException(String
.valueOf(trainOrders.gotoStatus));
}
this.gotoIcon.setPreferredSize(new Dimension(20, 20));
// Set consist
TrainListCellRenderer trainViewJPanel = (TrainListCellRenderer) consistChangeJPanel;
trainViewJPanel.display(trainOrders.trainNumber, index);
// Show priority orders.
if (trainOrders.isPriorityOrder) {
// Write the station name in upper case
String s = this.stationNameJLabel.getText();
this.stationNameJLabel.setText(s + " (Priority Orders)");
}
// Check for 'No change'
if (null == trainOrders.order.consist) {
if (trainOrders.order.autoConsist) {
this.noChangeJLabel.setText("Select wagons automatically");
} else {
this.noChangeJLabel.setText("No Change");
}
} else {
this.noChangeJLabel.setText(null);
}
// Set the section title
// this.sectionTitleJLabel.setText("trainOrders.sectionTitle");
return this;
}
Outgoing Methods (calls):
jfreerails.client.view.TrainOrderJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
gotoIcon = new javax.swing.JLabel();
consistChangeJPanel = new TrainListCellRenderer();
noChangeJLabel = new javax.swing.JLabel();
stationNameJLabel = new javax.swing.JLabel();
ordersJLabel = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
gotoIcon.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/jfreerails/client/graphics/selected_arrow.png")));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
add(gotoIcon, gridBagConstraints);
consistChangeJPanel.setLayout(new java.awt.GridBagLayout());
noChangeJLabel.setText("No Change");
consistChangeJPanel.add(noChangeJLabel,
new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
add(consistChangeJPanel, gridBagConstraints);
stationNameJLabel.setText("Some Station");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
add(stationNameJLabel, gridBagConstraints);
ordersJLabel.setText("wait until full / don't wait");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.ipadx = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 5);
add(ordersJLabel, gridBagConstraints);
}// GEN-END:initComponents
No outgoing methods.
jfreerails.client.view.TrainOrderJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
this.w = mr.getWorld();
TrainListCellRenderer trainViewJPanel = (TrainListCellRenderer) consistChangeJPanel;
trainViewJPanel.setHeight(15);
trainViewJPanel.setup(mr, vl, null);
this.principal = mr.getPrincipal();
}
Outgoing Methods (calls):
jfreerails.client.view.TrainOrdersListModel.fireRefresh
Javadoc:
No Javadoc available
Method code:
public void fireRefresh() {
super.fireContentsChanged(this, 0, getSize());
}
Outgoing Methods (calls):
jfreerails.client.view.TrainOrdersListModel.getElementAt
Javadoc:
No Javadoc available
Method code:
public Object getElementAt(int index) {
Schedule s = getSchedule();
int gotoStatus;
if (s.getNextScheduledOrder() == index) {
if (s.hasPriorityOrders()) {
gotoStatus = GOTO_AFTER_PRIORITY_ORDERS;
} else {
gotoStatus = GOTO_NOW;
}
} else {
if (s.hasPriorityOrders() && 0 == index) {
// These orders are the priority orders.
gotoStatus = GOTO_NOW;
} else {
gotoStatus = DONT_GOTO;
}
}
boolean isPriorityOrders = 0 == index && s.hasPriorityOrders();
TrainOrdersModel order = getSchedule().getOrder(index);
return new TrainOrdersListElement(isPriorityOrders, gotoStatus, order,
trainNumber);
}
Outgoing Methods (calls):
jfreerails.client.view.TrainOrdersListModel.getSchedule
Javadoc:
No Javadoc available
Method code:
private Schedule getSchedule() {
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
trainNumber);
ImmutableSchedule sched = null;
if (train != null) {
sched = (ImmutableSchedule) w.get(principal, KEY.TRAIN_SCHEDULES, train
.getScheduleID());
}
return sched;
}
Outgoing Methods (calls):
jfreerails.client.view.TrainOrdersListModel.getSize
Javadoc:
No Javadoc available
Method code:
public int getSize() {
Schedule s = getSchedule();
int size = 0;
if (s != null) {
size = s.getNumOrders();
}
return size;
}
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.addStationJButtonActionPerformed
Javadoc:
No Javadoc available
Method code:
private void addStationJButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addStationJButtonActionPerformed
MutableSchedule s = getSchedule();
try {
int newOrderNumber = s.addOrder(new TrainOrdersModel(
getFirstStationID(), null, false, false)); // TODO fix bug
showSelectStation(s, newOrderNumber);
} catch (NoSuchElementException e) {
logger
.warning("No stations exist so can't add station to schedule!");
}
}// GEN-LAST:event_addStationJButtonActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.addWagon
Javadoc:
No Javadoc available
Method code:
private void addWagon(int wagonTypeNumber) {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
int[] newConsist;
// The consist will be null if old orders were 'no change'.
if (null != oldOrders.consist) {
int oldLength = oldOrders.consist.size();
newConsist = new int[oldLength + 1];
// Copy existing wagons
for (int i = 0; i < oldLength; i++) {
newConsist[i] = oldOrders.consist.get(i);
}
// Then add specified wagon.
newConsist[oldLength] = wagonTypeNumber;
} else {
newConsist = new int[] { wagonTypeNumber };
}
newOrders = new TrainOrdersModel(oldOrders.getStationID(), new ImInts(
newConsist), oldOrders.getWaitUntilFull(), false);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.autoConsistJMenuItemActionPerformed
Javadoc:
No Javadoc available
Method code:
private void autoConsistJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_autoConsistJMenuItemActionPerformed
setAutoConsist();
}// GEN-LAST:event_autoConsistJMenuItemActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.changeStationActionPerformed
Javadoc:
/** * Handles the action event when the user selects a different station. * Retrieves the selected order index from the orders component and triggers * the station selection dialog using {@link #showSelectStation}. * * @param evt The ActionEvent object representing the user's interaction. * This parameter is not directly used in the method logic. */
Method code:
private void changeStationActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_changeStationActionPerformed
int orderNumber = this.orders.getSelectedIndex();
showSelectStation(this.getSchedule(), orderNumber);
}// GEN-LAST:event_changeStationActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.display
Javadoc:
No Javadoc available
Method code:
public void display(int newTrainNumber) {
this.trainNumber = newTrainNumber;
FreerailsPrincipal principal = modelRoot.getPrincipal();
ReadOnlyWorld w = modelRoot.getWorld();
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
newTrainNumber);
this.scheduleID = train.getScheduleID();
listModel = new TrainOrdersListModel(w, newTrainNumber, principal);
orders.setModel(listModel);
orders.setFixedCellWidth(250);
listModel.fireRefresh();
enableButtons();
}
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.dontWaitJMenuItemActionPerformed
Javadoc:
No Javadoc available
Method code:
private void dontWaitJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_dontWaitJMenuItemActionPerformed
setWaitUntilFull(false);
}// GEN-LAST:event_dontWaitJMenuItemActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.enableButtons
Javadoc:
No Javadoc available
Method code:
private void enableButtons() {
MutableSchedule s = getSchedule();
addStationJButton.setEnabled(s.canAddOrder());
// Only one set of priority orders are allowed.
priorityOrdersJButton.setEnabled(!s.hasPriorityOrders());
}
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.engineOnlyJMenuItemActionPerformed
Javadoc:
No Javadoc available
Method code:
private void engineOnlyJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_engineOnlyJMenuItemActionPerformed
removeAllWagons();
}// GEN-LAST:event_engineOnlyJMenuItemActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.getFirstStationID
Javadoc:
/** * Since stations can be removed, we should not assume that station 0 * exists: this method returns the id of the first station that exists. * */
Method code:
/**
* Since stations can be removed, we should not assume that station 0
* exists: this method returns the id of the first station that exists.
*
*/
private int getFirstStationID() {
NonNullElements stations = new NonNullElements(KEY.STATIONS, modelRoot
.getWorld(), modelRoot.getPrincipal());
if (stations.next()) {
return stations.getIndex();
}
throw new NoSuchElementException();
}
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.getSchedule
Javadoc:
No Javadoc available
Method code:
private MutableSchedule getSchedule() {
FreerailsPrincipal principal = modelRoot.getPrincipal();
ReadOnlyWorld w = modelRoot.getWorld();
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
trainNumber);
ImmutableSchedule immutableSchedule = (ImmutableSchedule) w.get(
principal, KEY.TRAIN_SCHEDULES, train.getScheduleID());
return new MutableSchedule(immutableSchedule);
}
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.gotoStationJMenuItemActionPerformed
Javadoc:
No Javadoc available
Method code:
private void gotoStationJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_gotoStationJMenuItemActionPerformed
MutableSchedule s = getSchedule();
int i = orders.getSelectedIndex();
s.setOrderToGoto(i);
sendUpdateMove(s);
}// GEN-LAST:event_gotoStationJMenuItemActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
trainOrderJPanel1 = new jfreerails.client.view.TrainOrderJPanel();
editOrderJPopupMenu = new javax.swing.JPopupMenu();
gotoStationJMenuItem = new javax.swing.JMenuItem();
changeStation = new javax.swing.JMenuItem();
removeStationJMenuItem = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JSeparator();
addWagonJMenu = new javax.swing.JMenu();
removeWagonsJMenu = new javax.swing.JMenu();
removeLastJMenuItem = new javax.swing.JMenuItem();
removeAllJMenuItem = new javax.swing.JMenuItem();
changeConsistJMenu = new javax.swing.JMenu();
noChangeJMenuItem = new javax.swing.JMenuItem();
engineOnlyJMenuItem = new javax.swing.JMenuItem();
autoConsistJMenuItem = new javax.swing.JMenuItem();
waitJMenu = new javax.swing.JMenu();
dontWaitJMenuItem = new javax.swing.JMenuItem();
waitUntilFullJMenuItem = new javax.swing.JMenuItem();
jSeparator2 = new javax.swing.JSeparator();
pullUpJMenuItem = new javax.swing.JMenuItem();
pushDownJMenuItem = new javax.swing.JMenuItem();
selectStationJPanel1 = new jfreerails.client.view.SelectStationJPanel();
selectStationJPopupMenu = new javax.swing.JPopupMenu();
this.selectStationJPopupMenu.add(selectStationJPanel1);
addStationJButton = new javax.swing.JButton();
priorityOrdersJButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
orders = new javax.swing.JList();
gotoStationJMenuItem.setText("Goto station");
gotoStationJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
gotoStationJMenuItemActionPerformed(evt);
}
});
editOrderJPopupMenu.add(gotoStationJMenuItem);
changeStation.setText("Change Station");
changeStation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
changeStationActionPerformed(evt);
}
});
editOrderJPopupMenu.add(changeStation);
removeStationJMenuItem.setText("Remove station");
removeStationJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeStationJMenuItemActionPerformed(evt);
}
});
editOrderJPopupMenu.add(removeStationJMenuItem);
editOrderJPopupMenu.add(jSeparator1);
addWagonJMenu.setText("Add Wagon");
editOrderJPopupMenu.add(addWagonJMenu);
removeWagonsJMenu.setText("Remove wagon(s)");
removeLastJMenuItem.setText("Remove last");
removeLastJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeLastJMenuItemActionPerformed(evt);
}
});
removeWagonsJMenu.add(removeLastJMenuItem);
removeAllJMenuItem.setText("Remove all wagons");
removeAllJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeAllJMenuItemActionPerformed(evt);
}
});
removeWagonsJMenu.add(removeAllJMenuItem);
editOrderJPopupMenu.add(removeWagonsJMenu);
changeConsistJMenu.setText("Change consist to..");
noChangeJMenuItem.setText("'No change'");
noChangeJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
noChangeJMenuItemActionPerformed(evt);
}
});
changeConsistJMenu.add(noChangeJMenuItem);
engineOnlyJMenuItem.setText("Engine only");
engineOnlyJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
engineOnlyJMenuItemActionPerformed(evt);
}
});
changeConsistJMenu.add(engineOnlyJMenuItem);
autoConsistJMenuItem.setText("Choose wagons automatically");
autoConsistJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
autoConsistJMenuItemActionPerformed(evt);
}
});
changeConsistJMenu.add(autoConsistJMenuItem);
editOrderJPopupMenu.add(changeConsistJMenu);
waitJMenu.setText("Wait at station");
dontWaitJMenuItem.setText("Don't wait");
dontWaitJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dontWaitJMenuItemActionPerformed(evt);
}
});
waitJMenu.add(dontWaitJMenuItem);
waitUntilFullJMenuItem.setText("Wait until full");
waitUntilFullJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
waitUntilFullJMenuItemActionPerformed(evt);
}
});
waitJMenu.add(waitUntilFullJMenuItem);
editOrderJPopupMenu.add(waitJMenu);
editOrderJPopupMenu.add(jSeparator2);
pullUpJMenuItem.setText("Pull up");
pullUpJMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pullUpJMenuItemActionPerformed(evt);
}
});
editOrderJPopupMenu.add(pullUpJMenuItem);
pushDownJMenuItem.setText("Push down");
pushDownJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pushDownJMenuItemActionPerformed(evt);
}
});
editOrderJPopupMenu.add(pushDownJMenuItem);
setLayout(new java.awt.GridBagLayout());
setBorder(new javax.swing.border.TitledBorder("Schedule"));
addStationJButton.setText("Add Station");
addStationJButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addStationJButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(addStationJButton, gridBagConstraints);
priorityOrdersJButton.setText("Add Priority Orders");
priorityOrdersJButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
priorityOrdersJButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(priorityOrdersJButton, gridBagConstraints);
jScrollPane1.setPreferredSize(new java.awt.Dimension(280, 160));
orders
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
orders.setCellRenderer(trainOrderJPanel1);
orders.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
ordersKeyPressed(evt);
}
});
orders.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
ordersMouseClicked(evt);
}
});
jScrollPane1.setViewportView(orders);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
add(jScrollPane1, gridBagConstraints);
}// GEN-END:initComponents
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.itemAdded
Javadoc:
No Javadoc available
Method code:
public void itemAdded(KEY key, int index, FreerailsPrincipal p) {
// do nothing.
}
No outgoing methods.
jfreerails.client.view.TrainScheduleJPanel.itemRemoved
Javadoc:
No Javadoc available
Method code:
public void itemRemoved(KEY key, int index, FreerailsPrincipal p) {
// do nothing.
}
No outgoing methods.
jfreerails.client.view.TrainScheduleJPanel.listUpdated
Javadoc:
No Javadoc available
Method code:
public void listUpdated(KEY key, int index, FreerailsPrincipal p) {
if (KEY.TRAIN_SCHEDULES == key && this.scheduleID == index) {
listModel.fireRefresh();
enableButtons();
}
}
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.noChange
Javadoc:
No Javadoc available
Method code:
private void noChange() {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
newOrders = new TrainOrdersModel(oldOrders.getStationID(), null, false,
false);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.noChangeJMenuItemActionPerformed
Javadoc:
No Javadoc available
Method code:
private void noChangeJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_noChangeJMenuItemActionPerformed
noChange();
}// GEN-LAST:event_noChangeJMenuItemActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.ordersKeyPressed
Javadoc:
No Javadoc available
Method code:
private void ordersKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_ordersKeyPressed
switch (evt.getKeyCode()) {
case KeyEvent.VK_O: {
// Add priority orders
priorityOrdersJButtonActionPerformed(null);
break;
}
case KeyEvent.VK_N: {
// Add station
addStationJButtonActionPerformed(null);
break;
}
default: {
// do nothing.
}
}
int orderNumber = this.orders.getSelectedIndex();
if (orderNumber == -1) {
// No order is selected.
return;
}
switch (evt.getKeyCode()) {
case KeyEvent.VK_G: {
// Goto station.
gotoStationJMenuItemActionPerformed(null);
break;
}
case KeyEvent.VK_S: {
// Change station
showSelectStation(this.getSchedule(), orderNumber);
break;
}
case KeyEvent.VK_A: {
// Auto schedule
setAutoConsist();
break;
}
case KeyEvent.VK_C: {
// Change add wagon
break;
}
case KeyEvent.VK_DELETE: {
// Remove station
removeStationJMenuItemActionPerformed(null);
break;
}
case KeyEvent.VK_BACK_SPACE: {
// Remove last wagon
removeLastWagon();
break;
}
case KeyEvent.VK_W: {
// toggle wait until full
MutableSchedule s = getSchedule();
TrainOrdersModel order = s.getOrder(orderNumber);
setWaitUntilFull(!order.waitUntilFull);
break;
}
default: {
// do nothing.
}
}
listModel.fireRefresh();
}// GEN-LAST:event_ordersKeyPressed
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.ordersMouseClicked
Javadoc:
No Javadoc available
Method code:
private void ordersMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_ordersMouseClicked
int i = orders.getSelectedIndex();
MutableSchedule s = getSchedule();
if (i >= s.getNumOrders()) {
// The selected index does not exist!
// For some reason, the JList hasn't updated yet.
i = -1;
}
if (-1 != i && java.awt.event.MouseEvent.BUTTON3 == evt.getButton()) {
// If an element is select and the right button is pressed.
TrainOrdersModel order = s.getOrder(i);
pullUpJMenuItem.setEnabled(s.canPullUp(i));
pushDownJMenuItem.setEnabled(s.canPushDown(i));
gotoStationJMenuItem.setEnabled(s.canSetGotoStation(i));
removeWagonsJMenu.setEnabled(order.orderHasWagons());
waitJMenu.setEnabled(order.orderHasWagons());
addWagonJMenu.setEnabled(order.hasLessThanMaximumNumberOfWagons());
setupWagonsPopup();
this.editOrderJPopupMenu.show(evt.getComponent(), evt.getX(), evt
.getY());
}
}// GEN-LAST:event_ordersMouseClicked
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.priorityOrdersJButtonActionPerformed
Javadoc:
No Javadoc available
Method code:
private void priorityOrdersJButtonActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_priorityOrdersJButtonActionPerformed
MutableSchedule s = getSchedule();
try {
s.setPriorityOrders(new TrainOrdersModel(getFirstStationID(), null,
false, false));// TODO fix bug
showSelectStation(s, Schedule.PRIORITY_ORDERS);
} catch (NoSuchElementException e) {
logger
.warning("No stations exist so can't add station to schedule!");
}
}// GEN-LAST:event_priorityOrdersJButtonActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.pullUpJMenuItemActionPerformed
Javadoc:
/** * Handles the action event when the "Pull Up" menu item is selected. * This method retrieves the current schedule, identifies the selected order index, * moves the selected order up in the schedule using the {@code pullUp} method, * sends an update to reflect the change via {@code sendUpdateMove}, and * updates the selected index to reflect the new position. * * @param evt The {@code ActionEvent} triggered by selecting the menu item. */
Method code:
private void pullUpJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pullUpJMenuItemActionPerformed
MutableSchedule s = getSchedule();
int i = orders.getSelectedIndex();
s.pullUp(i);
sendUpdateMove(s);
orders.setSelectedIndex(i - 1);
}// GEN-LAST:event_pullUpJMenuItemActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.pushDownJMenuItemActionPerformed
Javadoc:
No Javadoc available
Method code:
private void pushDownJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pushDownJMenuItemActionPerformed
MutableSchedule s = getSchedule();
int i = orders.getSelectedIndex();
s.pushDown(i);
sendUpdateMove(s);
orders.setSelectedIndex(i + 1);
}// GEN-LAST:event_pushDownJMenuItemActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.removeAllJMenuItemActionPerformed
Javadoc:
No Javadoc available
Method code:
private void removeAllJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_removeAllJMenuItemActionPerformed
removeAllWagons();
}// GEN-LAST:event_removeAllJMenuItemActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.removeAllWagons
Javadoc:
No Javadoc available
Method code:
private void removeAllWagons() {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
newOrders = new TrainOrdersModel(oldOrders.getStationID(),
new ImInts(), false, false);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.removeLastJMenuItemActionPerformed
Javadoc:
No Javadoc available
Method code:
private void removeLastJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_removeLastJMenuItemActionPerformed
removeLastWagon();
}// GEN-LAST:event_removeLastJMenuItemActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.removeLastWagon
Javadoc:
No Javadoc available
Method code:
private void removeLastWagon() {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
ImInts oldConsist = oldOrders.consist;
if( null == oldConsist){
//consist can be null if there is no
//scheduled change of wagons.
//Fixes freerails bug 1687677 and freerails2 bug 2014234
return;
}
int newLength = oldConsist.size() - 1;
if (newLength < 0) {
//No wagons to remove!
return;
}
ImInts newConsist = oldConsist.removeLast();
newOrders = new TrainOrdersModel(oldOrders.getStationID(), newConsist,
oldOrders.waitUntilFull, false);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.removeStationJMenuItemActionPerformed
Javadoc:
No Javadoc available
Method code:
private void removeStationJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_removeStationJMenuItemActionPerformed
MutableSchedule s = getSchedule();
if(s.getNumOrders() ==0){
logger.warning("Can't remove orders since non exist!");
return;
}
int i = orders.getSelectedIndex();
if(s.getNumOrders() <= i){
logger.warning("Order #"+String.valueOf(i)+" does not exist!");
return;
}
s.removeOrder(i);
sendUpdateMove(s);
}// GEN-LAST:event_removeStationJMenuItemActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.sendUpdateMove
Javadoc:
No Javadoc available
Method code:
private void sendUpdateMove(MutableSchedule mutableSchedule) {
FreerailsPrincipal principal = modelRoot.getPrincipal();
ReadOnlyWorld w = modelRoot.getWorld();
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
this.trainNumber);
// int scheduleID = train.getScheduleID();
assert (scheduleID == train.getScheduleID());
ImmutableSchedule before = (ImmutableSchedule) w.get(
principal, KEY.TRAIN_SCHEDULES, scheduleID);
ImmutableSchedule after = mutableSchedule.toImmutableSchedule();
Move m = new ChangeTrainScheduleMove(scheduleID, before, after,
principal);
this.modelRoot.doMove(m);
}
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.setAutoConsist
Javadoc:
No Javadoc available
Method code:
private void setAutoConsist() {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
newOrders = new TrainOrdersModel(oldOrders.getStationID(), null, false,
true);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.setWaitUntilFull
Javadoc:
No Javadoc available
Method code:
private void setWaitUntilFull(boolean b) {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
// If auto-consist is set do nothing
if (oldOrders.autoConsist)
return;
// If no-change is set do nothing
if (oldOrders.consist == null)
return;
boolean autoConsist = false;
newOrders = new TrainOrdersModel(oldOrders.getStationID(),
oldOrders.consist, b, autoConsist);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot mr, RenderersRoot vl, Action al) {
trainOrderJPanel1.setup(mr, vl, null);
this.modelRoot = mr;
this.vl = vl;
// This actionListener is fired by the select station popup when a
// station is selected.
Action action = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent evt) {
sendUpdateMove(selectStationJPanel1.generateNewSchedule());
selectStationJPopupMenu.setVisible(false);
listModel.fireRefresh();
orders.requestFocus();
}
};
this.selectStationJPanel1.setup(mr, vl, action);
}
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.setupWagonsPopup
Javadoc:
No Javadoc available
Method code:
private void setupWagonsPopup() {
addWagonJMenu.removeAll(); // Remove existing menu items.
NonNullElements cargoTypes = new NonNullElements(SKEY.CARGO_TYPES,
modelRoot.getWorld());
while (cargoTypes.next()) {
final CargoType wagonType = (CargoType) cargoTypes.getElement();
JMenuItem wagonMenuItem = new JMenuItem();
final int wagonTypeNumber = cargoTypes.getIndex();
wagonMenuItem.setText(wagonType.getDisplayName());
Image image = vl.getWagonImages(wagonTypeNumber).getSideOnImage();
int height = image.getHeight(null);
int width = image.getWidth(null);
int scale = height / 10;
ImageIcon icon = new ImageIcon(image.getScaledInstance(width
/ scale, height / scale, Image.SCALE_FAST));
wagonMenuItem.setIcon(icon);
wagonMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
addWagon(wagonTypeNumber);
}
});
addWagonJMenu.add(wagonMenuItem);
}
}
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.showSelectStation
Javadoc:
/** * Show the popup that lets the user select a station, called when a new * scheduled stop is added and when an existing scheduled stop is changed. */
Method code:
/**
* Show the popup that lets the user select a station, called when a new
* scheduled stop is added and when an existing scheduled stop is changed.
*/
private void showSelectStation(MutableSchedule schedule, int orderNumber) {
selectStationJPanel1.display(schedule, orderNumber);
// Show the select station popup in the middle of the window.
Container topLevelAncestor = this.getTopLevelAncestor();
Dimension d = topLevelAncestor.getSize();
Dimension d2 = selectStationJPopupMenu.getPreferredSize();
int x = Math.max((d.width - d2.width) / 2, 0);
int y = Math.max((d.height - d2.height) / 2, 0);
selectStationJPopupMenu.show(topLevelAncestor, x, y);
selectStationJPanel1.requestFocus();
}
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanel.waitUntilFullJMenuItemActionPerformed
Javadoc:
No Javadoc available
Method code:
private void waitUntilFullJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_waitUntilFullJMenuItemActionPerformed
setWaitUntilFull(true);
}// GEN-LAST:event_waitUntilFullJMenuItemActionPerformed
Outgoing Methods (calls):
jfreerails.client.view.TrainScheduleJPanelTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
//jpanel = new TrainScheduleJPanel();
//World w = MapFixtureFactory2.getCopy();
}
No outgoing methods.
jfreerails.client.view.TrainScheduleJPanelTest.testBug1384249
Javadoc:
No Javadoc available
Method code:
/*
* [ 1384249 ] Unexpected Exception: TrainScheduleJPanel.java line 661
*/
public void testBug1384249(){
}
No outgoing methods.
jfreerails.client.view.TrainSummaryJPanel.findMaintenanceCost
Javadoc:
No Javadoc available
Method code:
private String findMaintenanceCost() {
GameTime time = w.currentTime();
GameCalendar gameCalendar = (GameCalendar) w.get(ITEM.CALENDAR);
double month = gameCalendar.getMonth(time.getTicks());
long cost = (long) (month / 12 * 5000);
Money m = new Money(cost);
return "$" + m.toString();
}
Outgoing Methods (calls):
jfreerails.client.view.TrainSummaryJPanel.findStationName
Javadoc:
No Javadoc available
Method code:
private String findStationName(int trainNum) {
TrainOrdersModel orders = null;
TrainOrdersListModel ordersList = new TrainOrdersListModel(w, trainNum,
principal);
for (int i = 0; i < ordersList.getSize(); ++i) {
TrainOrdersListElement element = (TrainOrdersListElement) ordersList
.getElementAt(i);
if (element.gotoStatus == TrainOrdersListModel.GOTO_NOW) {
orders = element.order;
break;
}
}
StationModel station = (StationModel) w.get(principal, KEY.STATIONS, orders
.getStationID());
return station.getStationName();
}
Outgoing Methods (calls):
jfreerails.client.view.TrainSummaryJPanel.findTrainIncome
Javadoc:
No Javadoc available
Method code:
private String findTrainIncome(int trainNum) {
IncomeStatementGenerator income = new IncomeStatementGenerator(w,
principal);
Money m = income.calTrainRevenue(trainNum);
return "$" + m.toString();
}
Outgoing Methods (calls):
jfreerails.client.view.TrainSummaryJPanel.getListCellRendererComponent
Javadoc:
No Javadoc available
Method code:
public java.awt.Component getListCellRendererComponent(
javax.swing.JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
int trainID = NonNullElements
.row2index(w, KEY.TRAINS, principal, index);
trainNumLabel.setText("#" + (trainID + 1));
headingLabel.setText(findStationName(trainID));
trainMaintenanceCostLabel.setText(findMaintenanceCost());
trainIncomeLabel.setText(findTrainIncome(trainID));
java.awt.GridBagConstraints gridBagConstraints;
trainListCellRenderer1.setOpaque(true);
trainListCellRenderer1.setCenterTrain(false);
trainListCellRenderer1.display(trainID);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(3, 0, 3, 0);
add(trainListCellRenderer1, gridBagConstraints);
if (isSelected) {
if (list.isFocusOwner()) {
setBackground(selectedColor);
trainListCellRenderer1.setBackground(selectedColor);
} else {
setBackground(selectedColorNotFocused);
trainListCellRenderer1.setBackground(selectedColorNotFocused);
}
} else {
setBackground(backgroundColor);
trainListCellRenderer1.setBackground(backgroundColor);
}
// Set selected
return this;
}
Outgoing Methods (calls):
jfreerails.client.view.TrainSummaryJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
trainNumLabel = new javax.swing.JLabel();
headingLabel = new javax.swing.JLabel();
trainMaintenanceCostLabel = new javax.swing.JLabel();
trainIncomeLabel = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(500, 50));
trainNumLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
trainNumLabel.setText("jLabel1");
trainNumLabel
.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
trainNumLabel.setPreferredSize(new java.awt.Dimension(100, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
add(trainNumLabel, gridBagConstraints);
headingLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
headingLabel.setText("jLabel2");
headingLabel
.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
headingLabel.setPreferredSize(new java.awt.Dimension(100, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10);
add(headingLabel, gridBagConstraints);
trainMaintenanceCostLabel
.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
trainMaintenanceCostLabel.setText("jLabel3");
trainMaintenanceCostLabel.setMaximumSize(getMaximumSize());
trainMaintenanceCostLabel.setPreferredSize(new java.awt.Dimension(100,
25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10);
add(trainMaintenanceCostLabel, gridBagConstraints);
trainIncomeLabel
.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
trainIncomeLabel.setText("jLabel1");
trainIncomeLabel.setPreferredSize(new java.awt.Dimension(100, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
add(trainIncomeLabel, gridBagConstraints);
}// GEN-END:initComponents
No outgoing methods.
jfreerails.client.view.TrainSummaryJPanel.setup
Javadoc:
No Javadoc available
Method code:
public void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
this.principal = modelRoot.getPrincipal();
this.w = modelRoot.getWorld();
trainListCellRenderer1 = new TrainListCellRenderer(modelRoot, vl);
trainListCellRenderer1.setHeight(15);
}
Outgoing Methods (calls):
jfreerails.client.view.Unknown.actionPerformed
Javadoc:
No Javadoc available
Method code:
public void actionPerformed(ActionEvent arg0) {
Move bondTransaction = new AddTransactionMove(modelRoot
.getPrincipal(), BondTransaction.repayBond(5));
modelRoot.doMove(bondTransaction);
}
Outgoing Methods (calls):
jfreerails.client.view.Unknown.componentHidden
Javadoc:
No Javadoc available
Method code:
@Override
public void componentHidden(ComponentEvent e) {
}
No outgoing methods.
jfreerails.client.view.Unknown.componentShown
Javadoc:
No Javadoc available
Method code:
@Override
public void componentShown(ComponentEvent e) {
int i = wi.getIndex();
wi.reset();
if (i != WorldIterator.BEFORE_FIRST) {
wi.gotoIndex(i);
}
display();
}
Outgoing Methods (calls):
jfreerails.client.view.Unknown.propertyChange
Javadoc:
No Javadoc available
Method code:
public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName().equals(
StationBuildModel.StationBuildAction.STATION_POSITION_KEY)) {
/* update the renderer pos */
Point p = (Point) e.getNewValue();
stationRadiusRenderer.setPosition(p.x, p.y);
if (stationBuildModel.canBuildStationHere()) {
stationRadiusRenderer
.setBorderColor(StationRadiusRenderer.COLOR_OK);
} else {
stationRadiusRenderer
.setBorderColor(StationRadiusRenderer.COLOR_CANNOT_BUILD);
}
} else if (e.getPropertyName().equals(
StationBuildModel.StationBuildAction.STATION_RADIUS_KEY)) {
Integer radius = (Integer) e.getNewValue();
stationRadiusRenderer.setRadius(radius.intValue());
}
boolean enabled = stationBuildModel.getStationBuildAction()
.isEnabled();
if (buildEnabled != enabled) {
if (enabled) {
mapView.addMouseListener(StationPlacementCursor.this);
mapView.addMouseMotionListener(StationPlacementCursor.this);
stationRadiusRenderer.show();
} else {
stationRadiusRenderer.hide();
mapView.removeMouseListener(StationPlacementCursor.this);
mapView
.removeMouseMotionListener(StationPlacementCursor.this);
}
buildEnabled = enabled;
}
}
Outgoing Methods (calls):
jfreerails.client.view.View.setup
Javadoc:
No Javadoc available
Method code:
void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction);
No outgoing methods.
jfreerails.client.view.WagonCellRenderer.getListCellRendererComponent
Javadoc:
No Javadoc available
Method code:
public Component getListCellRendererComponent(JList list, Object value, /*
* value
* to
* display
*/
int index, /* cell index */
boolean isSelected, /* is the cell selected */
boolean cellHasFocus) /* the list and the cell have the focus */{
if (index >= 0 && index < labels.length) {
CargoType cargoType = (CargoType) value;
String text = "<html><body>"
+ (isSelected ? "<strong>" : "")
+ cargoType.getDisplayName()
+ (isSelected ? "</strong>"
: "&nbsp;&nbsp;&nbsp;&nbsp;"/*
* padding to stop
* word wrap due to
* greater width of
* strong font
*/) + "</body></html>";
((JLabel) labels[index]).setText(text);
return labels[index];
}
return null;
}
Outgoing Methods (calls):
jfreerails.client.view.World2ListModelAdapter.addListDataListener
Javadoc:
No Javadoc available
Method code:
public void addListDataListener(ListDataListener arg0) {
// TODO Auto-generated method stub
}
No outgoing methods.
jfreerails.client.view.World2ListModelAdapter.getElementAt
Javadoc:
No Javadoc available
Method code:
public Object getElementAt(int i) {
elements.gotoRow(i);
return elements.getElement();
}
Outgoing Methods (calls):
jfreerails.client.view.World2ListModelAdapter.getSize
Javadoc:
No Javadoc available
Method code:
public int getSize() {
return elements.size();
}
Outgoing Methods (calls):
jfreerails.client.view.World2ListModelAdapter.removeListDataListener
Javadoc:
No Javadoc available
Method code:
public void removeListDataListener(ListDataListener arg0) {
// TODO Auto-generated method stub
}
No outgoing methods.
jfreerails.controller.AddStationPreMove.addSupplyAndDemand
Javadoc:
No Javadoc available
Method code:
private CompositeMove addSupplyAndDemand(CompositeMove m, ReadOnlyWorld w) {
ImList<Move> moves2 = m.getMoves();
Move[] moves = new Move[moves2.size()];
for (int i = 0; i < moves2.size(); i++) {
moves[i] = moves2.get(i);
}
for (int i = 0; i < moves.length; i++) {
if (moves[i] instanceof AddItemToListMove) {
AddItemToListMove move = (AddItemToListMove) moves[i];
if (move.getKey().equals(KEY.STATIONS)) {
StationModel station = (StationModel) move.getAfter();
CalcCargoSupplyRateAtStation supplyRate;
supplyRate = new CalcCargoSupplyRateAtStation(w, station.x,
station.y, ruleNumber);
StationModel stationAfter = supplyRate
.calculations(station);
moves[i] = new AddItemToListMove(move.getKey(), move
.getIndex(), stationAfter, move.getPrincipal());
}
}
}
return new CompositeMove(moves);
}
Outgoing Methods (calls):
jfreerails.controller.AddStationPreMove.generateMove
Javadoc:
No Javadoc available
Method code:
public Move generateMove(ReadOnlyWorld world) {
TrackMoveTransactionsGenerator transactionsGenerator = new TrackMoveTransactionsGenerator(
world, principal);
FreerailsTile oldTile = (FreerailsTile) world.getTile(p.x, p.y);
String cityName;
String stationName;
FreerailsTile ft = (FreerailsTile)world.getTile(p.x, p.y);
TrackPiece before = ft.getTrackPiece();
TrackRule trackRule = (TrackRule) world.get(SKEY.TRACK_RULES,
this.ruleNumber);
int owner = ChangeTrackPieceCompositeMove.getOwner(principal, world);
TrackPiece after = new TrackPieceImpl(before.getTrackConfiguration(),
trackRule, owner, ruleNumber);
ChangeTrackPieceMove upgradeTrackMove = new ChangeTrackPieceMove(
before, after, p);
CompositeMove move;
if (!oldTile.getTrackPiece().getTrackRule().isStation()) {
// There isn't already a station here, we need to pick a name and
// add an entry
// to the station list.
CalcNearestCity cNC = new CalcNearestCity(world, p.x, p.y);
try {
cityName = cNC.findNearestCity();
VerifyStationName vSN = new VerifyStationName(world, cityName);
stationName = vSN.getName();
} catch (NoSuchElementException e) {
// there are no cities, this should never happen during a proper
// game. However
// some of the unit tests create stations when there are no
// cities.
stationName = "Central Station #"
+ world.size(principal, KEY.STATIONS);
}
// check the terrain to see if we can build a station on it...
move = AddStationMove.generateMove(world, stationName, p,
upgradeTrackMove, principal);
move = addSupplyAndDemand(move, world);
move = transactionsGenerator.addTransactions(move);
} else {
// Upgrade an existing station.
move = AddStationMove.upgradeStation(upgradeTrackMove);
}
return move;
}
Outgoing Methods (calls):
jfreerails.controller.AddStationPreMove.newStation
Javadoc:
No Javadoc available
Method code:
public static AddStationPreMove newStation(ImPoint p, int trackRule,
FreerailsPrincipal principal) {
return new AddStationPreMove(p, trackRule, principal);
}
No outgoing methods.
jfreerails.controller.AddStationPreMove.upgradeStation
Javadoc:
No Javadoc available
Method code:
public static AddStationPreMove upgradeStation(ImPoint p, int trackRule,
FreerailsPrincipal principal) {
return new AddStationPreMove(p, trackRule, principal);
}
No outgoing methods.
jfreerails.controller.AddTrainPreMove.calTrainLength
Javadoc:
No Javadoc available
Method code:
private int calTrainLength() {
TrainModel train = new TrainModel(engineTypeId, wagons, 0);
int length = train.getLength();
return length;
}
Outgoing Methods (calls):
jfreerails.controller.AddTrainPreMove.generateMove
Javadoc:
/** * Generates a move that does the following. * <ol> * <li>Adds the train</li> * <li>Adds a cargo bundle to represent the cargo the train is * carrying</li> * <li>Adds a schedule for the train</li> * <li>Adds transaction to pay for the train</li> * <li>Init. the trains position and motion</li> * </ol> * * */
Method code:
/**
* Generates a move that does the following.
* <ol>
* <li>Adds the train</li>
* <li>Adds a cargo bundle to represent the cargo the train is
* carrying</li>
* <li>Adds a schedule for the train</li>
* <li>Adds transaction to pay for the train</li>
* <li>Init. the trains position and motion</li>
* </ol>
*
*
*/
public Move generateMove(ReadOnlyWorld w) {
// Add cargo bundle.
int bundleId = w.size(principal, KEY.CARGO_BUNDLES);
ImmutableCargoBundle cargo = ImmutableCargoBundle.EMPTY_BUNDLE;
AddItemToListMove addCargoBundle = new AddItemToListMove(
KEY.CARGO_BUNDLES, bundleId, cargo, principal);
// Add schedule
for (int i = 0; i < schedule.getNumOrders(); i++) {
TrainOrdersModel order = schedule.getOrder(i);
if (!w.boundsContain(principal, KEY.STATIONS, order.stationId)) {
throw new ArrayIndexOutOfBoundsException(String.format("%d", order.stationId));
}
}
int scheduleId = w.size(principal, KEY.TRAIN_SCHEDULES);
AddItemToListMove addSchedule = new AddItemToListMove(
KEY.TRAIN_SCHEDULES, scheduleId, schedule, principal);
// Add train to train list.
TrainModel train = new TrainModel(engineTypeId, wagons, scheduleId,
bundleId);
int trainId = w.size(principal, KEY.TRAINS);
AddItemToListMove addTrain = new AddItemToListMove(KEY.TRAINS, trainId,
train, principal);
// Pay for train.
int quantity = 1;
/* Determine the price of the train. */
EngineType engineType = (EngineType) w.get(SKEY.ENGINE_TYPES,
engineTypeId);
Money price = engineType.getPrice();
Transaction transaction = new AddItemTransaction(
Transaction.Category.TRAIN, engineTypeId, quantity, new Money(
-price.getAmount()));
AddTransactionMove transactionMove = new AddTransactionMove(principal,
transaction);
// Setup and add train position.
PathOnTiles path = initPositionStep1(w);
TrainMotion motion = initPositionStep2(path);
Move addPosition = new AddActiveEntityMove(motion, trainId,
principal);
return new CompositeMove(addCargoBundle, addSchedule, addTrain,
transactionMove, addPosition);
}
Outgoing Methods (calls):
jfreerails.controller.AddTrainPreMove.initPositionStep1
Javadoc:
No Javadoc available
Method code:
PathOnTiles initPositionStep1(ReadOnlyWorld w) {
PositionOnTrack[] pp = FlatTrackExplorer.getPossiblePositions(w, point);
FlatTrackExplorer fte = new FlatTrackExplorer(w, pp[0]);
List<Step> steps = new ArrayList<Step>();
int length = calTrainLength();
int distanceTravelled = 0;
PositionOnTrack p = new PositionOnTrack();
while (distanceTravelled < length) {
fte.nextEdge();
fte.moveForward();
p.setValuesFromInt(fte.getPosition());
Step v = p.cameFrom();
distanceTravelled += v.getLength();
steps.add(v);
}
return new PathOnTiles(point, steps);
}
Outgoing Methods (calls):
jfreerails.controller.AddTrainPreMove.initPositionStep2
Javadoc:
No Javadoc available
Method code:
TrainMotion initPositionStep2(PathOnTiles path) {
// TODO fix code.
TrainMotion tm = new TrainMotion(path, path.steps(), calTrainLength(),
ConstAcc.STOPPED);
return tm;
}
Outgoing Methods (calls):
jfreerails.controller.AddTrainPreMoveTest.setupWorld
Javadoc:
No Javadoc available
Method code:
@Override
protected void setupWorld() {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
trackBuilder = new TrackMoveProducer(me, world, mr);
stationBuilder = new StationBuilder(me);
// Build track.
stationBuilder
.setStationType(stationBuilder.getTrackTypeID("terminal"));
Step[] track = {EAST, EAST, EAST, EAST, EAST, EAST, EAST, EAST, EAST};
stationA = new ImPoint(10, 10);
MoveStatus ms0 = trackBuilder.buildTrack(stationA, track);
assertTrue(ms0.ok);
// Build 2 stations.
MoveStatus ms1 = stationBuilder.buildStation(stationA);
assertTrue(ms1.ok);
stationB = new ImPoint(19, 10);
MoveStatus ms2 = stationBuilder.buildStation(stationB);
assertTrue(ms2.ok);
TrainOrdersModel order0 = new TrainOrdersModel(0, null, false, false);
TrainOrdersModel order1 = new TrainOrdersModel(1, null, false, false);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
defaultSchedule = s.toImmutableSchedule();
}
Outgoing Methods (calls):
jfreerails.controller.AddTrainPreMoveTest.testGetSchedule
Javadoc:
/** * Tests the {@link AddTrainPreMove} class's ability to generate and execute a move * that successfully creates a train target. This test verifies that the move sequence * correctly initializes a train using the provided track path and schedule. * * The test sets up a world, constructs a move executor, builds a track path, * generates a move via {@link AddTrainPreMove#generateMove}, and executes it. * It then asserts that the resulting train target is not null. * * @throws IllegalStateException if any step in the move execution fails, * indicating an invalid move or setup. */
Method code:
public void testGetSchedule() {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
TrackMoveProducer producer = new TrackMoveProducer(me, world, mr);
Step[] trackPath = {EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, WEST,
NORTH_WEST, NORTH, NORTH_EAST};
ImPoint from = new ImPoint(5, 5);
MoveStatus ms = producer.buildTrack(from, trackPath);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
TrainOrdersModel[] orders = {};
ImmutableSchedule is = new ImmutableSchedule(orders, -1, false);
AddTrainPreMove addTrain = new AddTrainPreMove(0, new ImInts(), from,
principal, is);
Move m = addTrain.generateMove(world);
ms = m.doMove(world, principal);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
TrainAccessor ta = new TrainAccessor(world, principal, 0);
assertNotNull(ta.getTarget());
}
Outgoing Methods (calls):
jfreerails.controller.AddTrainPreMoveTest.testInvalidSchedule
Javadoc:
No Javadoc available
Method code:
public void testInvalidSchedule() {
try {
TrainOrdersModel order0 = new TrainOrdersModel(10, null, false, false);
TrainOrdersModel order1 = new TrainOrdersModel(1, null, false, false);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
ImmutableSchedule invalidSchedule = s.toImmutableSchedule();
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0),
stationA, principal, invalidSchedule);
preMove.generateMove(world);
fail();
} catch (ArrayIndexOutOfBoundsException e) {
}
}
Outgoing Methods (calls):
jfreerails.controller.AddTrainPreMoveTest.testMove
Javadoc:
No Javadoc available
Method code:
@Override
public void testMove() {
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0),
stationA, principal, defaultSchedule);
Move m = preMove.generateMove(world);
assertDoMoveIsOk(m);
assertUndoMoveIsOk(m);
assertSurvivesSerialisation(m);
}
Outgoing Methods (calls):
jfreerails.controller.AddTrainPreMoveTest.testMove2
Javadoc:
No Javadoc available
Method code:
public void testMove2() {
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0),
stationA, principal, defaultSchedule);
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.ok);
ActivityIterator ai = world.getActivities(principal, 0);
TrainMotion tm = (TrainMotion) ai.getActivity();
assertEquals(0d, tm.duration());
assertEquals(0d, tm.getSpeedAtEnd());
assertEquals(0d, tm.getDistance(0));
PositionOnTrack pot = tm.getFinalPosition();
assertNotNull(pot);
assertEquals(EAST, pot.facing());
assertEquals(13, pot.getX());
assertEquals(10, pot.getY());
}
Outgoing Methods (calls):
jfreerails.controller.AddTrainPreMoveTest.testPathOnTiles
Javadoc:
/** * Check that the path on tiles created for the new train is actually on * the track. */
Method code:
/**
* Check that the path on tiles created for the new train is actually on
* the track.
*/
public void testPathOnTiles() {
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0),
stationA, principal, defaultSchedule);
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.ok);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
TrainMotion motion = ta.findCurrentMotion(0);
assertNotNull(motion);
PathOnTiles path = motion.getTiles(motion.duration());
assertTrackHere(path);
}
Outgoing Methods (calls):
jfreerails.controller.BalanceSheetGenerator.calTrackTotal
Javadoc:
No Javadoc available
Method code:
public static Money calTrackTotal(Transaction.Category category,
ReadOnlyWorld w, FreerailsPrincipal principal, GameTime startTime) {
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, principal);
aggregator.setCategory(TRACK);
long amount = 0;
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
long trackValue = trackRule.getPrice().getAmount();
GameTime[] times = new GameTime[] { startTime,
GameTime.END_OF_THE_WORLD };
aggregator.setType(i);
aggregator.setTimes(times);
ItemsTransactionAggregator.QuantitiesAndValues qnv = aggregator
.calculateQuantitiesAndValues();
int quantity = qnv.quantities[0];
amount += trackValue * quantity
/ TrackConfiguration.LENGTH_OF_STRAIGHT_TRACK_PIECE;
}
return new Money(amount);
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackExplorer.canBuildTrack
Javadoc:
/** * <p> * Tests whether we can build track in the direction specified by * m_direction. * </p> * * <p> * If we enter a tile from a given direction, the tiles we can build track * to depend on the following. (1) The terrain type of the surrounding tiles - * track can only be built on certain terrain types. (2) The direction we * entered the current tile from. (3) Any existing track on the current tile - * limits possible track configurations. (4) The terrain type of the current * tile - terrain type determines which track types and hence which track * configurations can be built. * </p> * */
Method code:
/**
* <p>
* Tests whether we can build track in the direction specified by
* m_direction.
* </p>
*
* <p>
* If we enter a tile from a given direction, the tiles we can build track
* to depend on the following. (1) The terrain type of the surrounding tiles -
* track can only be built on certain terrain types. (2) The direction we
* entered the current tile from. (3) Any existing track on the current tile -
* limits possible track configurations. (4) The terrain type of the current
* tile - terrain type determines which track types and hence which track
* configurations can be built.
* </p>
*
*/
private boolean canBuildTrack() {
// Check that we are not doubling back on ourselves.
Step opposite2current = currentPosition.cameFrom().getOpposite();
int currentX = currentPosition.getX();
int currentY = currentPosition.getY();
int directionWeCameFrom = opposite2current.getID();
int directionWeCameFromPlus = (directionWeCameFrom + 1) % 8;
int directionWeCameFromMinus = (directionWeCameFrom + 7) % 8;
if (directionInt == directionWeCameFrom
|| directionInt == directionWeCameFromPlus
|| directionInt == directionWeCameFromMinus) {
return false;
}
// Check that we are not going off the map.
Step directionOfNextTile = Step.getInstance(directionInt);
int newX = currentX + directionOfNextTile.getDx();
int newY = currentY + directionOfNextTile.getDy();
if (!world.boundsContain(newX, newY)) {
return false;
}
TrackRule rule4nextTile;
TrackRule rule4lastTile;
// Determine the track rule for the next tile.
final FreerailsTile nextTile = (FreerailsTile) world.getTile(newX,
newY);
// Check there is not another players track at nextTile.
if (nextTile.hasTrack()) {
if (nextTile.getTrackPiece().getOwnerID() != world.getID(principal)) {
return false;
}
}
rule4nextTile = getAppropriateTrackRule(newX, newY);
if (null == rule4nextTile) {
return false; // We can't build track on the tile.
}
rule4lastTile = getAppropriateTrackRule(currentX, currentY);
if (null == rule4lastTile) {
return false; // We can't build track on the tile.
}
// Determine the track rule for the current tile.
FreerailsTile currentTile = (FreerailsTile) world.getTile(currentX,
currentY);
// Check for illegal track configurations.
final TrackConfiguration trackAlreadyPresent1 = currentTile
.getTrackPiece().getTrackConfiguration();
final TrackConfiguration trackAlreadyPresent2 = nextTile
.getTrackPiece().getTrackConfiguration();
TrackConfiguration fromConfig = trackAlreadyPresent1;
fromConfig = TrackConfiguration.add(fromConfig, opposite2current);
fromConfig = TrackConfiguration.add(fromConfig, TILE_CENTER);
Step goingTo = Step.getInstance(directionInt);
fromConfig = TrackConfiguration.add(fromConfig, goingTo);
if (!rule4lastTile.trackPieceIsLegal(fromConfig)) {
return false;
}
// Check for diagonal conflicts.
if (directionOfNextTile.isDiagonal()) {
int x2check = currentX;
int y2check = currentY + directionOfNextTile.deltaY;
// We did a bounds check above.
assert (world.boundsContain(x2check, y2check));
FreerailsTile tile2Check = (FreerailsTile) world.getTile(x2check,
y2check);
TrackConfiguration config2check = tile2Check
.getTrackPiece().getTrackConfiguration();
Step vector2check = Step.getInstance(directionOfNextTile.deltaX,
-directionOfNextTile.deltaY);
if (config2check.contains(vector2check)) {
// then we have a diagonal conflict.
return false;
}
}
// Check for illegal track configurations on the tile we are entering.
TrackConfiguration fromConfig2 = trackAlreadyPresent2;
fromConfig2 = TrackConfiguration.add(fromConfig2, TILE_CENTER);
Step goingBack = Step.getInstance(directionInt).getOpposite();
fromConfig2 = TrackConfiguration.add(fromConfig2, goingBack);
if (!rule4nextTile.trackPieceIsLegal(fromConfig2)) {
return false;
}
/*
* Set the using existing track. We do this because a path that uses
* existing track is cheaper to build.
*/
usingExistingTrack = trackAlreadyPresent1.contains(goingTo);
return true;
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackExplorer.getAppropriateTrackRule
Javadoc:
No Javadoc available
Method code:
private TrackRule getAppropriateTrackRule(int x, int y) {
final FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
TrackRule rule;
if (!tile.hasTrack()) {
int terrainTypeID = tile.getTerrainTypeID();
int trackRuleID = buildTrackStrategy.getRule(terrainTypeID);
if (trackRuleID == -1) {
return null; // Can't build on this terrain!
}
rule = (TrackRule) world.get(SKEY.TRACK_RULES, trackRuleID);
} else {
rule = tile.getTrackPiece().getTrackRule();
}
return rule;
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackExplorer.getEdgeCost
Javadoc:
/** * Calculates a cost figure incorporating the distance and the cost of any * new track. */
Method code:
/**
* Calculates a cost figure incorporating the distance and the cost of any
* new track.
*/
public int getEdgeCost() {
if (beforeFirst) {
throw new IllegalStateException();
}
Step edgeDirection = Step.getInstance(directionInt - 1);
double length = edgeDirection.getLength();
final int DISTANCE_COST = 10000; // Same as the cost of standard
// track.
int cost = (int) Math.round(DISTANCE_COST * length);
if (!usingExistingTrack) {
int[] x = { currentPosition.getX(),
currentPosition.getX() + edgeDirection.deltaX };
int[] y = { currentPosition.getY(),
currentPosition.getY() + edgeDirection.deltaY };
TrackRule ruleA = getAppropriateTrackRule(x[0], y[0]);
TrackRule ruleB = getAppropriateTrackRule(x[1], y[1]);
/*
* If there is a station at either of the points, don't include its
* price in the cost calculation since it has already been paid.
* Otherwise, add the cost of building the track.
*/
long priceA = ruleA.getPrice().getAmount();
long priceB = ruleB.getPrice().getAmount();
cost += length * (priceA + priceB);
// Add fixed cost if tile b does not have the desired track type.
FreerailsTile a = (FreerailsTile) world.getTile(x[0], y[0]);
TrackRule currentRuleA = a.getTrackPiece().getTrackRule();
if (!currentRuleA.equals(ruleA)) {
assert (!currentRuleA.isStation()); // We shouldn't be upgrading
// a station.
cost += ruleA.getFixedCost().getAmount() * Step.TILE_DIAMETER;
}
}
return cost;
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackExplorer.getH
Javadoc:
No Javadoc available
Method code:
public int getH() {
int xDistance = (target.x - currentPosition.getX())
* Step.TILE_DIAMETER;
int yDistance = (target.y - currentPosition.getY())
* Step.TILE_DIAMETER;
int sumOfSquares = (xDistance * xDistance + yDistance * yDistance);
return (int) Math.sqrt(sumOfSquares);
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackExplorer.getPosition
Javadoc:
No Javadoc available
Method code:
public int getPosition() {
return currentPosition.toInt();
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackExplorer.getVertexConnectedByEdge
Javadoc:
No Javadoc available
Method code:
public int getVertexConnectedByEdge() {
if (beforeFirst) {
throw new IllegalStateException();
}
return currentBranch.toInt();
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackExplorer.hasNextEdge
Javadoc:
No Javadoc available
Method code:
public boolean hasNextEdge() {
while (directionInt < 8) {
if (canBuildTrack()) {
return true;
}
directionInt++;
}
return false;
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackExplorer.moveForward
Javadoc:
No Javadoc available
Method code:
public void moveForward() {
if (beforeFirst) {
throw new IllegalStateException();
}
setPosition(this.getVertexConnectedByEdge());
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackExplorer.nextEdge
Javadoc:
No Javadoc available
Method code:
public void nextEdge() {
if (!hasNextEdge()) {
throw new NoSuchElementException();
}
// The direction we are moving relative to the current position.
Step direction = Step.getInstance(directionInt);
currentBranch.setCameFrom(direction);
currentBranch.setX(currentPosition.getX() + direction.getDx());
currentBranch.setY(currentPosition.getY() + direction.getDy());
directionInt++;
beforeFirst = false;
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackExplorer.setBuildTrackStrategy
Javadoc:
No Javadoc available
Method code:
public void setBuildTrackStrategy(BuildTrackStrategy trackStrategy) {
if (null == trackStrategy)
throw new NullPointerException();
buildTrackStrategy = trackStrategy;
}
No outgoing methods.
jfreerails.controller.BuildTrackExplorer.setPosition
Javadoc:
No Javadoc available
Method code:
public void setPosition(int vertex) {
currentPosition.setValuesFromInt(vertex);
directionInt = 0;
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackExplorerTest.assertNextVertexIs
Javadoc:
No Javadoc available
Method code:
private void assertNextVertexIs(Step oneTileMoveVector, int x, int y,
BuildTrackExplorer explorer) {
assertTrue(explorer.hasNextEdge());
explorer.nextEdge();
PositionOnTrack pos = new PositionOnTrack(explorer
.getVertexConnectedByEdge());
assertEquals(PositionOnTrack.createComingFrom(x, y, oneTileMoveVector),
pos);
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackExplorerTest.buildTrack
Javadoc:
No Javadoc available
Method code:
private void buildTrack(int x, int y, Step direction) {
TrackRule rule = (TrackRule) world.get(SKEY.TRACK_RULES, 0);
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(new ImPoint(x, y), direction, rule,
rule, world, MapFixtureFactory.TEST_PRINCIPAL);
MoveStatus ms = move.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.ok);
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackExplorerTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
world = new WorldImpl(20, 20);
world.addPlayer(testPlayer);
world.set(ITEM.GAME_RULES, GameRules.NO_RESTRICTIONS);
principal = testPlayer.getPrincipal();
MapFixtureFactory.generateTrackRuleList(world);
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackExplorerTest.test1
Javadoc:
/** * On a blank map, we should be able to build track in any direction as long * as it does not go off the map. */
Method code:
/**
* On a blank map, we should be able to build track in any direction as long
* as it does not go off the map.
*/
public void test1() {
PositionOnTrack start;
// Test starting in the middle of the map.
start = PositionOnTrack.createComingFrom(10, 10, Step.NORTH);
BuildTrackExplorer explorer = new BuildTrackExplorer(world, principal);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.NORTH, 10, 9, explorer);
assertNextVertexIs(Step.NORTH_EAST, 11, 9, explorer);
assertNextVertexIs(Step.EAST, 11, 10, explorer);
// We miss out SW, S, and SE since we don't want to double back on
// ourselves.
assertNextVertexIs(Step.WEST, 9, 10, explorer);
assertNextVertexIs(Step.NORTH_WEST, 9, 9, explorer);
assertFalse(explorer.hasNextEdge());
// Test starting in the top left of the map.
start = PositionOnTrack.createComingFrom(0, 0, Step.SOUTH_EAST);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.EAST, 1, 0, explorer);
assertNextVertexIs(Step.SOUTH_EAST, 1, 1, explorer);
assertNextVertexIs(Step.SOUTH, 0, 1, explorer);
assertFalse(explorer.hasNextEdge());
// Test starting in the bottom right of the map.
start = PositionOnTrack.createComingFrom(19, 19, Step.NORTH_WEST);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.NORTH, 19, 18, explorer);
assertNextVertexIs(Step.WEST, 18, 19, explorer);
assertNextVertexIs(Step.NORTH_WEST, 18, 18, explorer);
assertFalse(explorer.hasNextEdge());
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackExplorerTest.test2
Javadoc:
/** Test when we cannot build on some terrain types. */
Method code:
/** Test when we cannot build on some terrain types. */
public void test2() {
// Check the the Ocean type is where we think it is.
int oceanTypeNumber = 4;
TileTypeImpl ocean = (TileTypeImpl) world.get(SKEY.TERRAIN_TYPES,
oceanTypeNumber);
assertEquals(TerrainType.Category.Ocean, ocean.getCategory());
// Check that track cannot be built on ocean.
for (int i = 0; i < world.size(SKEY.TRACK_RULES); i++) {
TrackRule rule = (TrackRule) world.get(SKEY.TRACK_RULES, i);
assertFalse(rule.canBuildOnThisTerrainType(ocean.getCategory()));
}
// Place some ocean.
FreerailsTile tile = FreerailsTile.getInstance(oceanTypeNumber);
world.setTile(10, 9, tile);
world.setTile(11, 10, tile);
PositionOnTrack start;
// Test starting in the middle of the map.
start = PositionOnTrack.createComingFrom(10, 10, Step.NORTH);
BuildTrackExplorer explorer = new BuildTrackExplorer(world, principal);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.NORTH_EAST, 11, 9, explorer);
// We miss out SW, S, and SE since we don't want to double back on
// ourselves.
assertNextVertexIs(Step.WEST, 9, 10, explorer);
assertNextVertexIs(Step.NORTH_WEST, 9, 9, explorer);
assertFalse(explorer.hasNextEdge());
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackExplorerTest.test3
Javadoc:
/** Test for illegal track configurations. */
Method code:
/** Test for illegal track configurations. */
public void test3() {
// Build some track, from 10, 10 diagonally SE.
int y = 10;
int x = 10;
for (int i = 0; i < 4; i++) {
Step v = Step.SOUTH_EAST;
buildTrack(x, y, v);
x += v.deltaX;
y += v.deltaY;
}
// If we enter 10, 10 from the south, we should be able to build track S
// & SW.
PositionOnTrack start = PositionOnTrack.createComingFrom(10, 10,
Step.SOUTH);
BuildTrackExplorer explorer = new BuildTrackExplorer(world, principal);
explorer.setPosition(start.toInt());
// SE is going along existing track
assertNextVertexIs(Step.SOUTH_EAST, 11, 11, explorer);
// S is building new track.
assertNextVertexIs(Step.SOUTH, 10, 11, explorer);
assertFalse(explorer.hasNextEdge());
// If we enter 10, 11 from the north, we should be able to build track
// N, E, W, & NW.
start = PositionOnTrack.createComingFrom(10, 11, Step.NORTH);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.NORTH, 10, 10, explorer);
assertNextVertexIs(Step.EAST, 11, 11, explorer);
assertNextVertexIs(Step.WEST, 9, 11, explorer);
assertNextVertexIs(Step.NORTH_WEST, 9, 10, explorer);
assertFalse(explorer.hasNextEdge());
// If we enter 10, 12 from the north, we also should be able to build
// track N, E, W, & NW.
start = PositionOnTrack.createComingFrom(10, 12, Step.NORTH);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.NORTH, 10, 11, explorer);
assertNextVertexIs(Step.EAST, 11, 12, explorer);
assertNextVertexIs(Step.WEST, 9, 12, explorer);
assertNextVertexIs(Step.NORTH_WEST, 9, 11, explorer);
assertFalse(explorer.hasNextEdge());
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackStrategy.generateRules
Javadoc:
No Javadoc available
Method code:
private static int[] generateRules(ArrayList<Integer> allowable,
ReadOnlyWorld w) {
int noTerrainTypes = w.size(SKEY.TERRAIN_TYPES);
int[] newRules = new int[noTerrainTypes];
for (int i = 0; i < noTerrainTypes; i++) {
TerrainType terrainType = (TerrainType) w
.get(SKEY.TERRAIN_TYPES, i);
newRules[i] = -1; // the default value.
for (Integer rule : allowable) {
if (null != rule) {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES,
rule.intValue());
if (trackRule.canBuildOnThisTerrainType(terrainType
.getCategory())) {
newRules[i] = rule.intValue();
break;
}
}
}
}
return newRules;
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackStrategy.getCheapest
Javadoc:
No Javadoc available
Method code:
private static Integer getCheapest(TrackRule.TrackCategories category,
ReadOnlyWorld w) {
TrackRule cheapest = null;
Integer cheapestID = null;
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule rule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
if (rule.getCategory().equals(category)) {
if (null == cheapest
|| cheapest.getPrice().getAmount() > rule.getPrice()
.getAmount()) {
cheapest = rule;
cheapestID = new Integer(i);
}
}
}
return cheapestID;
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackStrategy.getDefault
Javadoc:
No Javadoc available
Method code:
public static BuildTrackStrategy getDefault(ReadOnlyWorld w) {
ArrayList<Integer> allowable = new ArrayList<Integer>();
allowable.add(getCheapest(TrackRule.TrackCategories.track, w));
allowable.add(getCheapest(TrackRule.TrackCategories.bridge, w));
allowable.add(getCheapest(TrackRule.TrackCategories.tunnel, w));
return new BuildTrackStrategy(generateRules(allowable, w));
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackStrategy.getMultipleRuleInstance
Javadoc:
No Javadoc available
Method code:
public static BuildTrackStrategy getMultipleRuleInstance(
ArrayList<Integer> ruleIDs, ReadOnlyWorld w) {
int[] rulesArray = generateRules(ruleIDs, w);
return new BuildTrackStrategy(rulesArray);
}
Outgoing Methods (calls):
jfreerails.controller.BuildTrackStrategy.getRule
Javadoc:
No Javadoc available
Method code:
public int getRule(int terrainType) {
return rules[terrainType];
}
No outgoing methods.
jfreerails.controller.BuildTrackStrategy.getSingleRuleInstance
Javadoc:
No Javadoc available
Method code:
public static BuildTrackStrategy getSingleRuleInstance(int trackTypeID,
ReadOnlyWorld w) {
int noTerrainTypes = w.size(SKEY.TERRAIN_TYPES);
int[] newRules = new int[noTerrainTypes];
for (int i = 0; i < noTerrainTypes; i++) {
newRules[i] = trackTypeID;
}
return new BuildTrackStrategy(newRules);
}
Outgoing Methods (calls):
jfreerails.controller.CalcCargoSupplyRateAtStation.calculations
Javadoc:
/** * * Process each existing station, updating what is supplied to it. * * @param station * A StationModel object to be processed * */
Method code:
/**
*
* Process each existing station, updating what is supplied to it.
*
* @param station
* A StationModel object to be processed
*
*/
public StationModel calculations(StationModel station) {
int[] cargoSupplied = new int[w.size(SKEY.CARGO_TYPES)];
Vector<CargoElementObject> supply = scanAdjacentTiles();
// grab the supply rates from the vector
for (int i = 0; i < supply.size(); i++) {
cargoSupplied[i] = supply.get(i).getRate();
}
// set the supply rates for the current station
SupplyAtStation supplyAtStation = new SupplyAtStation(cargoSupplied);
station = new StationModel(station, supplyAtStation);
station = new StationModel(station, getDemand());
station = new StationModel(station, getConversion());
return station;
}
Outgoing Methods (calls):
jfreerails.controller.CalcCargoSupplyRateAtStation.findTrackRule
Javadoc:
No Javadoc available
Method code:
private static int findTrackRule(int xx, int yy, ReadOnlyWorld w) {
FreerailsTile tile = (FreerailsTile) w.getTile(xx, yy);
int ruleNumber = tile.getTrackPiece().getTrackTypeID();
return ruleNumber;
}
Outgoing Methods (calls):
jfreerails.controller.CalcCargoSupplyRateAtStation.getConversion
Javadoc:
No Javadoc available
Method code:
public ConvertedAtStation getConversion() {
return new ConvertedAtStation(this.converts);
}
No outgoing methods.
jfreerails.controller.CalcCargoSupplyRateAtStation.getDemand
Javadoc:
No Javadoc available
Method code:
public Demand4Cargo getDemand() {
boolean[] demandboolean = new boolean[w.size(SKEY.CARGO_TYPES)];
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
if (demand[i] >= PREREQUISITE_FOR_DEMAND) {
demandboolean[i] = true;
}
}
return new Demand4Cargo(demandboolean);
}
Outgoing Methods (calls):
jfreerails.controller.CalcCargoSupplyRateAtStation.incrementSupplyAndDemand
Javadoc:
No Javadoc available
Method code:
private void incrementSupplyAndDemand(int i, int j) {
int tileTypeNumber = ((FreerailsTile) w.getTile(i, j))
.getTerrainTypeID();
TerrainType terrainType = (TerrainType) w.get(SKEY.TERRAIN_TYPES,
tileTypeNumber);
// Calculate supply.
ImList<Production> production = terrainType.getProduction();
// loop through the production array and increment
// the supply rates for the station
for (int m = 0; m < production.size(); m++) {
int type = production.get(m).getCargoType();
int rate = production.get(m).getRate();
// loop through supplies vector and increment the cargo values as
// required
updateSupplyRate(type, rate);
}
// Now calculate demand.
ImList<Consumption> consumption = terrainType.getConsumption();
for (int m = 0; m < consumption.size(); m++) {
int type = consumption.get(m).getCargoType();
int prerequisite = consumption.get(m).getPrerequisite();
// The prerequisite is the number tiles of this type that must
// be within the station radius before the station demands the
// cargo.
demand[type] += PREREQUISITE_FOR_DEMAND / prerequisite;
}
ImList<Conversion> conversion = terrainType.getConversion();
for (int m = 0; m < conversion.size(); m++) {
int type = conversion.get(m).getInput();
// Only one tile that converts the cargo type is needed for the
// station to demand the cargo type.
demand[type] += PREREQUISITE_FOR_DEMAND;
converts[type] = conversion.get(m).getOutput();
}
}
Outgoing Methods (calls):
jfreerails.controller.CalcCargoSupplyRateAtStation.populateSuppliesVector
Javadoc:
No Javadoc available
Method code:
private void populateSuppliesVector() {
// fill supplies vector with 0 values for all cargo types
// get the correct list of cargoes from the world object
CargoElementObject tempCargoElement;
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
// cT = (CargoType) w.get(SKEY.CARGO_TYPES, i);
tempCargoElement = new CargoElementObject(0, i);
supplies.add(tempCargoElement);
}
}
Outgoing Methods (calls):
jfreerails.controller.CalcCargoSupplyRateAtStation.scanAdjacentTiles
Javadoc:
No Javadoc available
Method code:
public Vector<CargoElementObject> scanAdjacentTiles() {
int stationDiameter = stationRadius * 2 + 1;
Rectangle stationRadiusRect = new Rectangle(x - stationRadius, y
- stationRadius, stationDiameter, stationDiameter);
Rectangle mapRect = new Rectangle(0, 0, w.getMapWidth(), w
.getMapHeight());
Rectangle tiles2scan = stationRadiusRect.intersection(mapRect);
logger.fine("stationRadiusRect=" + stationRadiusRect);
logger.fine("mapRect=" + mapRect);
logger.fine("tiles2scan=" + tiles2scan);
// Look at the terrain type of each tile and retrieve the cargo
// supplied.
// The station radius determines how many tiles each side we look at.
for (int i = tiles2scan.x; i < (tiles2scan.x + tiles2scan.width); i++) {
for (int j = tiles2scan.y; j < (tiles2scan.y + tiles2scan.height); j++) {
incrementSupplyAndDemand(i, j);
}
}
// return the supplied cargo rates
return supplies;
}
Outgoing Methods (calls):
jfreerails.controller.CalcCargoSupplyRateAtStation.updateSupplyRate
Javadoc:
No Javadoc available
Method code:
private void updateSupplyRate(int type, int rate) {
// loop through supplies vector and increment the cargo values as
// required
for (int n = 0; n < supplies.size(); n++) {
CargoElementObject tempElement = supplies.elementAt(n);
if (tempElement.getType() == type) {
// cargo types are the same, so increment the rate in supply
// with the rate.
tempElement.setRate(tempElement.getRate() + rate);
break; // no need to go through the rest if we've found a match
}
}
}
Outgoing Methods (calls):
jfreerails.controller.CalcNearestCity.findNearestCity
Javadoc:
No Javadoc available
Method code:
public String findNearestCity() {
double cityDistance;
String cityName = null;
double tempDistance;
CityModel tempCity;
if (w.size(SKEY.CITIES) > 0) {
tempCity = (CityModel) w.get(SKEY.CITIES, 0);
cityDistance = getDistance(tempCity.getCityX(), tempCity.getCityY());
cityName = tempCity.getCityName();
for (int i = 1; i < w.size(SKEY.CITIES); i++) {
tempCity = (CityModel) w.get(SKEY.CITIES, i);
tempDistance = getDistance(tempCity.getCityX(), tempCity
.getCityY());
if (tempDistance < cityDistance) {
cityDistance = tempDistance;
cityName = tempCity.getCityName();
}
}
return cityName;
}
throw new NoSuchElementException();
}
Outgoing Methods (calls):
jfreerails.controller.CalcNearestCity.getDistance
Javadoc:
No Javadoc available
Method code:
private double getDistance(int cityX, int cityY) {
double distance = 0;
double a = (this.x - cityX) * (this.x - cityX);
double b = (this.y - cityY) * (this.y - cityY);
distance = Math.sqrt(a + b);
return distance;
}
No outgoing methods.
jfreerails.controller.CargoElementObject.getRate
Javadoc:
No Javadoc available
Method code:
public int getRate() {
return rate;
}
No outgoing methods.
jfreerails.controller.CargoElementObject.getType
Javadoc:
No Javadoc available
Method code:
public int getType() {
return type;
}
No outgoing methods.
jfreerails.controller.CargoElementObject.setRate
Javadoc:
/** * Sets the rate for this cargo element. * * @param rate The rate value to set. */
Method code:
public void setRate(int rate) {
this.rate = rate;
}
No outgoing methods.
jfreerails.controller.ClientControlInterface.setGameModel
Javadoc:
/** Called when a new game is started or a game is loaded. */
Method code:
/** Called when a new game is started or a game is loaded. */
void setGameModel(FreerailsMutableSerializable world);
No outgoing methods.
jfreerails.controller.ClientControlInterface.setProperty
Javadoc:
/** Sets a property, for example, the list of saved games. */
Method code:
/** Sets a property, for example, the list of saved games. */
void setProperty(ClientProperty propertyName, Serializable value);
No outgoing methods.
jfreerails.controller.CopyableTextJPanel.copyItemActionPerformed
Javadoc:
No Javadoc available
Method code:
private void copyItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copyItemActionPerformed
jTextArea1.copy();
}//GEN-LAST:event_copyItemActionPerformed
No outgoing methods.
jfreerails.controller.CopyableTextJPanel.initComponents
Javadoc:
/** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */
Method code:
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jPopupMenu1 = new javax.swing.JPopupMenu();
copyItem = new javax.swing.JMenuItem();
selectAllItem = new javax.swing.JMenuItem();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
copyItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
copyItem.setText("Copy");
copyItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
copyItemActionPerformed(evt);
}
});
jPopupMenu1.add(copyItem);
selectAllItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
selectAllItem.setText("Select All");
selectAllItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectAllItemActionPerformed(evt);
}
});
jPopupMenu1.add(selectAllItem);
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(500, 300));
jTextArea1.setEditable(false);
jTextArea1.setText("dsfasd\n\nsad\nf\nasd\nfa\nsdf\nas\ndf\nas\ndf\nads\nf\nasd\nf\nads\nf\ndsa\nf\ndsa\nf\ndasf\na\ndsf\nads\nf\nasd\nf\nasd\nf\n\nasdf");
jTextArea1.setWrapStyleWord(true);
jTextArea1.setOpaque(false);
jTextArea1.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextArea1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTextArea1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}
Outgoing Methods (calls):
jfreerails.controller.CopyableTextJPanel.jTextArea1MouseClicked
Javadoc:
No Javadoc available
Method code:
private void jTextArea1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextArea1MouseClicked
if(SwingUtilities.isRightMouseButton(evt)){
jPopupMenu1.show(jTextArea1, evt.getX(), evt.getY());
}
}//GEN-LAST:event_jTextArea1MouseClicked
No outgoing methods.
jfreerails.controller.CopyableTextJPanel.selectAllItemActionPerformed
Javadoc:
No Javadoc available
Method code:
private void selectAllItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectAllItemActionPerformed
jTextArea1.selectAll();
}//GEN-LAST:event_selectAllItemActionPerformed
No outgoing methods.
jfreerails.controller.CopyableTextJPanel.setText
Javadoc:
No Javadoc available
Method code:
public void setText(String s){
this.jTextArea1.setText(s);
}
No outgoing methods.
jfreerails.controller.DropOffAndPickupCargoMoveGenerator.generateMove
Javadoc:
No Javadoc available
Method code:
public Move generateMove() {
// The methods that calculate the before and after bundles could be
// called from here.
ChangeCargoBundleMove changeAtStation = new ChangeCargoBundleMove(stationBefore
.toImmutableCargoBundle(), stationAfter.toImmutableCargoBundle(), stationBundleId,
principal);
ChangeCargoBundleMove changeOnTrain = new ChangeCargoBundleMove(trainBefore
.toImmutableCargoBundle(), trainAfter.toImmutableCargoBundle(), trainBundleId,
principal);
moves.add(TransferCargoAtStationMove.CHANGE_AT_STATION_INDEX, changeAtStation);
moves.add(TransferCargoAtStationMove.CHANGE_ON_TRAIN_INDEX, changeOnTrain);
if (autoConsist) {
int engine = train.getTrain().getEngineType();
Move m = ChangeTrainMove.generateMove(this.trainId, train.getTrain(), engine, consist, principal);
moves.add(m);
} else if (waitingForFullLoad) {
// Only generate a move if there is some cargo to add..
if (changeOnTrain.beforeEqualsAfter())
return null;
}
TransferCargoAtStationMove move = new TransferCargoAtStationMove(moves, waitingForFullLoad);
assert move.getChangeAtStation() == changeAtStation;
assert move.getChangeOnTrain() == changeOnTrain;
return move;
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGenerator.getBundles
Javadoc:
No Javadoc available
Method code:
private void getBundles() {
TrainModel trainModel = ((TrainModel) w.get(principal, KEY.TRAINS, trainId));
trainBundleId = trainModel.getCargoBundleID();
trainBefore = getCopyOfBundle(trainBundleId);
trainAfter = getCopyOfBundle(trainBundleId);
StationModel stationModel = ((StationModel) w.get(principal, KEY.STATIONS, stationId));
stationBundleId = stationModel.getCargoBundleID();
stationAfter = getCopyOfBundle(stationBundleId);
stationBefore = getCopyOfBundle(stationBundleId);
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGenerator.getCopyOfBundle
Javadoc:
No Javadoc available
Method code:
private MutableCargoBundle getCopyOfBundle(int id) {
FreerailsSerializable fs = w.get(principal, KEY.CARGO_BUNDLES, id);
ImmutableCargoBundle ibundle = (ImmutableCargoBundle) fs;
return new MutableCargoBundle(ibundle);
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGenerator.isCargo2Transfer
Javadoc:
No Javadoc available
Method code:
public boolean isCargo2Transfer() {
ImInts spaceAvailable = train.spaceAvailable();
int total = 0;
for (int cargoType = 0; cargoType < w.size(SKEY.CARGO_TYPES); cargoType++) {
int quantity = spaceAvailable.get(cargoType);
int amount2transfer = Math.min(quantity, stationAfter
.getAmount(cargoType));
total += amount2transfer;
}
return total > 0;
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGenerator.processStationBundle
Javadoc:
/** Transfer cargo from the station to the train subject to the space available on the train. */
Method code:
/** Transfer cargo from the station to the train subject to the space available on the train.
*/
private void processStationBundle() {
ImInts spaceAvailable = TrainAccessor.spaceAvailable2(w, trainAfter.toImmutableCargoBundle(), consist);
for (int cargoType = 0; cargoType < spaceAvailable.size(); cargoType++) {
int quantity = spaceAvailable.get(cargoType);
int amount2transfer = Math.min(quantity, stationAfter
.getAmount(cargoType));
transferCargo(cargoType, amount2transfer, stationAfter, trainAfter);
}
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGenerator.processTrainBundle
Javadoc:
No Javadoc available
Method code:
private void processTrainBundle() {
Iterator<CargoBatch> batches = trainAfter.toImmutableCargoBundle().cargoBatchIterator();
StationModel station = (StationModel) w.get(principal, KEY.STATIONS, stationId);
MutableCargoBundle cargoDroppedOff = new MutableCargoBundle();
// Unload the cargo that the station demands
while (batches.hasNext()) {
CargoBatch cb = batches.next();
// if the cargo is demanded and its not from this station
// originally...
Demand4Cargo demand = station.getDemand();
int cargoType = cb.getCargoType();
if ((demand.isCargoDemanded(cargoType)) && (stationId != cb.getStationOfOrigin())) {
int amount = trainAfter.getAmount(cb);
cargoDroppedOff.addCargo(cb, amount);
// Now perform any conversions..
ConvertedAtStation converted = station.getConverted();
if (converted.isCargoConverted(cargoType)) {
int newCargoType = converted.getConversion(cargoType);
CargoBatch newCargoBatch = new CargoBatch(newCargoType, station.x, station.y,
0, stationId);
stationAfter.addCargo(newCargoBatch, amount);
}
trainAfter.setAmount(cb, 0);
}
}
moves = ProcessCargoAtStationMoveGenerator.processCargo(w, cargoDroppedOff, this.stationId,
principal, trainId);
// Unload the cargo that there isn't space for on the train regardless
// of whether the station
// demands it.
ImInts spaceAvailable = train.spaceAvailable();
for (int cargoType = 0; cargoType < spaceAvailable.size(); cargoType++) {
int quantity = spaceAvailable.get(cargoType);
if (quantity < 0) {
int amount2transfer = -quantity;
transferCargo(cargoType, amount2transfer, trainAfter, stationAfter);
}
}
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGenerator.transferCargo
Javadoc:
/** * Move the specified quantity of the specified cargotype from one bundle to * another. */
Method code:
/**
* Move the specified quantity of the specified cargotype from one bundle to
* another.
*/
private static void transferCargo(int cargoTypeToTransfer, int amountToTransfer,
MutableCargoBundle from, MutableCargoBundle to) {
if (0 == amountToTransfer) {
return;
}
Iterator<CargoBatch> batches = from.toImmutableCargoBundle().cargoBatchIterator();
int amountTransferredSoFar = 0;
while (batches.hasNext() && amountTransferredSoFar < amountToTransfer) {
CargoBatch cb = batches.next();
if (cb.getCargoType() == cargoTypeToTransfer) {
int amount = from.getAmount(cb);
int amountOfThisBatchToTransfer;
if (amount < amountToTransfer - amountTransferredSoFar) {
amountOfThisBatchToTransfer = amount;
from.setAmount(cb, 0);
} else {
amountOfThisBatchToTransfer = amountToTransfer - amountTransferredSoFar;
from.addCargo(cb, -amountOfThisBatchToTransfer);
}
to.addCargo(cb, amountOfThisBatchToTransfer);
amountTransferredSoFar += amountOfThisBatchToTransfer;
}
}
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest.addWagons
Javadoc:
No Javadoc available
Method code:
private void addWagons(ImInts wagons) {
TrainModel train = (TrainModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.TRAINS,
0);
TrainModel newTrain = train.getNewInstance(train.getEngineType(),
wagons);
w.set(MapFixtureFactory.TEST_PRINCIPAL, KEY.TRAINS, 0, newTrain);
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest.getCargoAtStation
Javadoc:
/** * Retrieves the cargo bundle that is waiting at the station from the world * object. */
Method code:
/**
* Retrieves the cargo bundle that is waiting at the station from the world
* object.
*/
private ImmutableCargoBundle getCargoAtStation() {
StationModel station = (StationModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
0);
ImmutableCargoBundle cargoAtStation = (ImmutableCargoBundle) w.get(
MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES,
station.getCargoBundleID());
return cargoAtStation;
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest.getCargoOnTrain
Javadoc:
/** * Retrieves the cargo bundle that the train is carrying from the world * object. */
Method code:
/**
* Retrieves the cargo bundle that the train is carrying from the world
* object.
*/
private ImmutableCargoBundle getCargoOnTrain() {
TrainModel train = (TrainModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.TRAINS,
0);
ImmutableCargoBundle cargoOnTrain = (ImmutableCargoBundle) w.get(
MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES,
train.getCargoBundleID());
return cargoOnTrain;
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest.main
Javadoc:
No Javadoc available
Method code:
public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest.removeAllWagonsFromTrain
Javadoc:
No Javadoc available
Method code:
private void removeAllWagonsFromTrain() {
addWagons(new ImInts());
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest.setCargoAtStation
Javadoc:
No Javadoc available
Method code:
private void setCargoAtStation(CargoBatch cb, int amount) {
StationModel station = (StationModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
0);
MutableCargoBundle bundle = new MutableCargoBundle(getCargoAtStation());
bundle.setAmount(cb, amount);
w.set(MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES, station.getCargoBundleID(), bundle
.toImmutableCargoBundle());
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest.setCargoOnTrain
Javadoc:
No Javadoc available
Method code:
private void setCargoOnTrain(CargoBatch cb, int amount) {
TrainModel train = (TrainModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.TRAINS,
0);
MutableCargoBundle bundle = new MutableCargoBundle(getCargoOnTrain());
bundle.setAmount(cb, amount);
w.set(MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES, train.getCargoBundleID(), bundle
.toImmutableCargoBundle());
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
// Set up the world object with three cargo types, one station, and one
// train.
w = new WorldImpl();
w.addPlayer(MapFixtureFactory.TEST_PLAYER);
// set up the cargo types.
w.add(SKEY.CARGO_TYPES, new CargoType(0, "Mail", Categories.Mail));
w.add(SKEY.CARGO_TYPES, new CargoType(0, "Passengers",
Categories.Passengers));
w.add(SKEY.CARGO_TYPES, new CargoType(0, "Goods",
Categories.Fast_Freight));
// Set up station
int x = 10;
int y = 10;
int stationCargoBundleId = w.add(MapFixtureFactory.TEST_PRINCIPAL,
KEY.CARGO_BUNDLES,
ImmutableCargoBundle.EMPTY_BUNDLE);
String stationName = "Station 1";
StationModel station = new StationModel(x, y, stationName, w
.size(SKEY.CARGO_TYPES), stationCargoBundleId);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, station);
// Set up train
int trainCargoBundleId = w.add(MapFixtureFactory.TEST_PRINCIPAL,
KEY.CARGO_BUNDLES,
ImmutableCargoBundle.EMPTY_BUNDLE);
// 3 wagons to carry cargo type 0.
ImInts wagons = new ImInts(0, 0, 0);
TrainModel train = new TrainModel(wagons, trainCargoBundleId);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.TRAINS, train);
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest.stopAtStation
Javadoc:
/** * Tests the generation of a move for stopping at a station. * Creates an instance of {@code DropOffAndPickupCargoMoveGenerator}, * generates a move, and verifies that the move execution results in * {@code MoveStatus.MOVE_OK}. * * @param w The world state used for move execution (assumed to be an instance variable). */
Method code:
private void stopAtStation() {
DropOffAndPickupCargoMoveGenerator moveGenerator = new DropOffAndPickupCargoMoveGenerator(
0, 0, w, MapFixtureFactory.TEST_PRINCIPAL, false, false);
Move m = moveGenerator.generateMove();
if(null != m){
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
assertEquals(MoveStatus.MOVE_OK, ms);
}
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest.suite
Javadoc:
/** * Constructs and returns a JUnit test suite for the * {@link DropOffAndPickupCargoMoveGeneratorTest} class. * * @return A TestSuite instance containing all test cases for this class. */
Method code:
private static junit.framework.Test suite() {
junit.framework.TestSuite testSuite = new junit.framework.TestSuite(
DropOffAndPickupCargoMoveGeneratorTest.class);
return testSuite;
}
No outgoing methods.
jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest.testDontDropOffCargo
Javadoc:
/** * Tests that a train does not drop cargo off at its station of origin * unless it has to. */
Method code:
/**
* Tests that a train does not drop cargo off at its station of origin
* unless it has to.
*/
public void testDontDropOffCargo() {
// Set station to
setCargoOnTrain(cargoType0FromStation0, 50);
setCargoOnTrain(cargoType0FromStation2, 50);
stopAtStation();
// The train shouldn't have dropped anything off.
MutableCargoBundle expectedOnTrain = new MutableCargoBundle();
expectedOnTrain.setAmount(cargoType0FromStation0, 50);
expectedOnTrain.setAmount(cargoType0FromStation2, 50);
assertEquals(expectedOnTrain.toImmutableCargoBundle(),
getCargoOnTrain());
assertEquals(ImmutableCargoBundle.EMPTY_BUNDLE, getCargoAtStation());
// Now remove the wagons from the train.
removeAllWagonsFromTrain();
stopAtStation();
/*
* The train now has no wagons, so must drop off the cargo whether the
* station demands it or not. Since the station does not demand it, the
* cargo should get added to the cargo waiting at the station.
*/
MutableCargoBundle expectedAtStation = new MutableCargoBundle();
expectedAtStation.setAmount(cargoType0FromStation0, 50);
expectedAtStation.setAmount(cargoType0FromStation2, 50);
assertEquals(expectedAtStation.toImmutableCargoBundle(),
getCargoAtStation());
assertEquals(ImmutableCargoBundle.EMPTY_BUNDLE, getCargoOnTrain());
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest.testDropOffCargo
Javadoc:
/** * Tests that a train drops of cargo that a station demands and does not * drop off cargo that is not demanded unless it has to. */
Method code:
/**
* Tests that a train drops of cargo that a station demands and does not
* drop off cargo that is not demanded unless it has to.
*/
public void testDropOffCargo() {
// Set the station to demand cargo type 0.
StationModel station = (StationModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
0);
Demand4Cargo demand = new Demand4Cargo(new boolean[] { true,
false, false, false });
station = new StationModel(station, demand);
w.set(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, 0, station);
// Check that the station demands what we think it does.
assertTrue("The station should demand cargo type 0.", station
.getDemand().isCargoDemanded(0));
assertFalse("The station shouldn't demand cargo type 1.", station
.getDemand().isCargoDemanded(1));
// Add 2 wagons for cargo type 0 and 1 for cargo type 1 to train.
ImInts wagons = new ImInts(0, 0, 1, 1);
addWagons(wagons);
// Add quantities of cargo type 0 and 2 to the train.
setCargoOnTrain(this.cargoType0FromStation2, 50);
setCargoOnTrain(this.cargoType1FromStation2, 40);
stopAtStation();
/*
* The train should have dropped of the 50 units cargo of type 0 since
* the station demands it but not the 40 units of cargo type 1 which is
* does not demand.
*/
MutableCargoBundle expectedOnTrain = new MutableCargoBundle();
expectedOnTrain.setAmount(this.cargoType1FromStation2, 40);
assertEquals(expectedOnTrain.toImmutableCargoBundle(),
getCargoOnTrain());
assertEquals(ImmutableCargoBundle.EMPTY_BUNDLE, getCargoAtStation());
// Now remove the wagons from the train.
removeAllWagonsFromTrain();
stopAtStation();
/*
* This time the train has no wagons, so has to drop the 40 units of
* cargo type 1 even though the station does not demand it. Since ths
* station does not demand it, it is added to the cargo waiting at the
* station.
*/
MutableCargoBundle expectedAtStation = new MutableCargoBundle();
expectedAtStation.setAmount(this.cargoType1FromStation2, 40);
assertEquals(expectedAtStation.toImmutableCargoBundle(),
getCargoAtStation());
assertEquals(ImmutableCargoBundle.EMPTY_BUNDLE, getCargoOnTrain());
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest.testPickUpAndDropOffSameCargoType
Javadoc:
/** * Tests that a train drops off any cargo before picking up cargo. */
Method code:
/**
* Tests that a train drops off any cargo before picking up cargo.
*/
public void testPickUpAndDropOffSameCargoType() {
// Set cargo at station and on train.
setCargoOnTrain(this.cargoType0FromStation2, 120);
setCargoAtStation(this.cargoType0FromStation0, 200);
// Set station to demand cargo 0.
StationModel station = (StationModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
0);
Demand4Cargo demand = new Demand4Cargo(new boolean[] { true,
false, false, false });
station = new StationModel(station, demand);
w.set(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, 0, station);
assertTrue(station.getDemand().isCargoDemanded(0));
stopAtStation();
MutableCargoBundle expectedOnTrain = new MutableCargoBundle();
expectedOnTrain.setAmount(this.cargoType0FromStation0, 120);
MutableCargoBundle expectedAtStation = new MutableCargoBundle();
expectedAtStation.setAmount(this.cargoType0FromStation0, 80);
assertEquals(expectedOnTrain.toImmutableCargoBundle(),
getCargoOnTrain());
assertEquals(expectedAtStation.toImmutableCargoBundle(),
getCargoAtStation());
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest.testPickUpCargo1
Javadoc:
/** Tests picking up cargo from a station. */
Method code:
/** Tests picking up cargo from a station. */
public void testPickUpCargo1() {
// Set up the variables for this test.
MutableCargoBundle cargoBundleWith2CarloadsOfCargo0 = new MutableCargoBundle();
// cargoBundleWith2CarloadsOfCargo0.setAmount(cargoType0FromStation2,
// 2);
cargoBundleWith2CarloadsOfCargo0.setAmount(cargoType0FromStation2, 80);
assertEquals("There shouldn't be any cargo at the station yet",
ImmutableCargoBundle.EMPTY_BUNDLE, getCargoAtStation());
assertEquals("There shouldn't be any cargo on the train yet",
ImmutableCargoBundle.EMPTY_BUNDLE, getCargoOnTrain());
// Now add 2 carloads of cargo type 0 to the station.
// getCargoAtStation().setAmount(cargoType0FromStation2, 2);
setCargoAtStation(cargoType0FromStation2, 80);
// The train should pick up this cargo, since it has three wagons
// capable of carrying cargo type 0.
stopAtStation();
// The train should now have the two car loads of cargo and there should
// be no cargo at the station.
assertEquals("There should no longer be any cargo at the station",
ImmutableCargoBundle.EMPTY_BUNDLE, getCargoAtStation());
assertEquals("The train should now have the two car loads of cargo",
cargoBundleWith2CarloadsOfCargo0.toImmutableCargoBundle(),
getCargoOnTrain());
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest.testPickUpCargo2
Javadoc:
/** * Tests picking up cargo when the there is too much cargo at the station * for the train to carry. */
Method code:
/**
* Tests picking up cargo when the there is too much cargo at the station
* for the train to carry.
*/
public void testPickUpCargo2() {
setCargoAtStation(this.cargoType0FromStation2, 200);
stopAtStation();
// The train has 3 wagons, each wagon carries 40 units of cargo, so
// the train should pickup 120 units of cargo.
MutableCargoBundle expectedOnTrain = new MutableCargoBundle();
expectedOnTrain.setAmount(this.cargoType0FromStation2, 120);
// The remaining 80 units of cargo should be left at the station.
MutableCargoBundle expectedAtStation = new MutableCargoBundle();
expectedAtStation.setAmount(this.cargoType0FromStation2, 80);
// Test the expected values against the actuals..
assertEquals(expectedOnTrain.toImmutableCargoBundle(),
getCargoOnTrain());
assertEquals(expectedAtStation.toImmutableCargoBundle(),
getCargoAtStation());
}
Outgoing Methods (calls):
jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest.testPickUpCargo3
Javadoc:
/** * Tests that a train takes into account how much cargo it already has and * the type of wagons it has when it is picking up cargo. */
Method code:
/**
* Tests that a train takes into account how much cargo it already has and
* the type of wagons it has when it is picking up cargo.
*/
public void testPickUpCargo3() {
ImInts wagons = new ImInts(0, 0, 2, 2);
// 2 wagons for cargo type 0; 2 wagons for cargo type 2.
addWagons(wagons);
// Set cargo on train.
setCargoOnTrain(this.cargoType0FromStation2, 30);
// Set cargo at station.
setCargoAtStation(this.cargoType0FromStation0, 110);
// Check that station does not demand cargo type 0.
StationModel station = (StationModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
0);
assertFalse(station.getDemand().isCargoDemanded(0));
// Stop at station.
stopAtStation();
/*
* The train has 2 wagons for cargo type 0 but had 30 units of cargo
* type 0 before stopping so it can only pick up 50 units.
*/
MutableCargoBundle expectedAtStation = new MutableCargoBundle();
expectedAtStation.setAmount(cargoType0FromStation0, 60);
MutableCargoBundle expectedOnTrain = new MutableCargoBundle();
expectedOnTrain.setAmount(this.cargoType0FromStation2, 30);
expectedOnTrain.setAmount(this.cargoType0FromStation0, 50);
assertEquals(expectedAtStation.toImmutableCargoBundle(),
getCargoAtStation());
assertEquals(expectedOnTrain.toImmutableCargoBundle(),
getCargoOnTrain());
}
Outgoing Methods (calls):
jfreerails.controller.FinancialDataGatherer.bondInterestRates
Javadoc:
/** * Retrieves an array of bond interest rates. * <p> * This method is intended to gather bond interest rate data. The returned array * contains interest rates for various bonds or time periods. The current * implementation returns null as a placeholder; the actual implementation * should populate and return the data. * * @return an array of integers representing bond interest rates, or null if * data is not yet available. */
Method code:
public int[] bondInterestRates() {
return null;
}
No outgoing methods.
jfreerails.controller.FinancialDataGatherer.canBuyStock
Javadoc:
No Javadoc available
Method code:
public boolean canBuyStock() {
return totalShares > 0;
}
No outgoing methods.
jfreerails.controller.FinancialDataGatherer.canIssueBond
Javadoc:
No Javadoc available
Method code:
public boolean canIssueBond() {
return nextBondInterestRate() <= 7;
}
Outgoing Methods (calls):
jfreerails.controller.FinancialDataGatherer.changeStake
Javadoc:
No Javadoc available
Method code:
public void changeStake(int stakeHolder, int deltaStock) {
}
No outgoing methods.
jfreerails.controller.FinancialDataGatherer.changeTreasuryStock
Javadoc:
No Javadoc available
Method code:
public void changeTreasuryStock(int deltaStock) {
}
No outgoing methods.
jfreerails.controller.FinancialDataGatherer.condition
Javadoc:
No Javadoc available
Method code:
@Override
protected boolean condition(int transactionID) {
// We'll do the work when incrementRunningTotal gets called.
return true;
}
No outgoing methods.
jfreerails.controller.FinancialDataGatherer.getBonds
Javadoc:
No Javadoc available
Method code:
public int getBonds() {
return bonds;
}
No outgoing methods.
jfreerails.controller.FinancialDataGatherer.getStockInRRs
Javadoc:
No Javadoc available
Method code:
public int[] getStockInRRs() {
return stockInRRs;
}
No outgoing methods.
jfreerails.controller.FinancialDataGatherer.getStockInThisRRs
Javadoc:
No Javadoc available
Method code:
public int[] getStockInThisRRs() {
if(null == stockInThisRRs){
stockInThisRRs = new int[w.getNumberOfPlayers()];
for(int i = 0; i < w.getNumberOfPlayers(); i++){
Player p = w.getPlayer(i);
FinancialDataGatherer temp = new FinancialDataGatherer(w, p.getPrincipal());
stockInThisRRs[i] = temp.stockInRRs[this.playerID];
}
}
return stockInThisRRs;
}
Outgoing Methods (calls):
jfreerails.controller.FinancialDataGatherer.incrementRunningTotal
Javadoc:
No Javadoc available
Method code:
@Override
protected void incrementRunningTotal(int transactionID) {
Transaction t = super.w.getTransaction(super.principal, transactionID);
if (t instanceof AddItemTransaction) {
AddItemTransaction ait = (AddItemTransaction) t;
if (t instanceof StockTransaction
&& ait.getCategory() == Transaction.Category.ISSUE_STOCK
&& ait.getType() == -1) {
// If it is a change in the total number of shares issued.
StockTransaction ist = (StockTransaction) t;
totalShares += ist.getQuantity();
} else if (t instanceof StockTransaction
&& ait.getCategory() == Transaction.Category.TRANSFER_STOCK
) {
//
stockInRRs[ait.getType()] += ait.getQuantity();
} else if (t instanceof BondTransaction) {
bonds += ait.getQuantity();
}
} else {
super.incrementRunningTotal(transactionID);
}
}
Outgoing Methods (calls):
jfreerails.controller.FinancialDataGatherer.netWorth
Javadoc:
No Javadoc available
Method code:
public Money netWorth() {
NetWorthCalculator nwc = new NetWorthCalculator(w, principal);
GameTime[] times = {GameTime.BIG_BANG, GameTime.END_OF_THE_WORLD};
nwc.setTimes(times);
return nwc.calculateValue();
}
Outgoing Methods (calls):
jfreerails.controller.FinancialDataGatherer.nextBondInterestRate
Javadoc:
No Javadoc available
Method code:
public int nextBondInterestRate() {
EconomicClimate ec = (EconomicClimate) w.get(ITEM.ECONOMIC_CLIMATE);
return bonds + ec.getBaseInterestRate();
}
Outgoing Methods (calls):
jfreerails.controller.FinancialDataGatherer.setTotalsArrayLength
Javadoc:
No Javadoc available
Method code:
@Override
protected void setTotalsArrayLength(int length) {
// TODO Auto-generated method stub
super.setTotalsArrayLength(length);
}
Outgoing Methods (calls):
jfreerails.controller.FinancialDataGatherer.sharesHeldByPublic
Javadoc:
No Javadoc available
Method code:
public int sharesHeldByPublic(){
int[]stock = getStockInThisRRs();
int returnValue = this.totalShares;
for (int i = 0; i < stock.length; i++) {
returnValue -= stock[i];
}
return returnValue;
}
Outgoing Methods (calls):
jfreerails.controller.FinancialDataGatherer.storeRunningTotal
Javadoc:
No Javadoc available
Method code:
@Override
protected void storeRunningTotal(int timeIndex) {
// TODO Auto-generated method stub
super.storeRunningTotal(timeIndex);
}
Outgoing Methods (calls):
jfreerails.controller.FinancialDataGatherer.thisRRHasStakeIn
Javadoc:
No Javadoc available
Method code:
public boolean thisRRHasStakeIn(int otherReId){
return stockInRRs[otherReId] > 0;
}
No outgoing methods.
jfreerails.controller.FinancialDataGatherer.totalShares
Javadoc:
/** Returns The number of open Shares */
Method code:
/** Returns The number of open Shares */
public int totalShares() {
return totalShares;
}
No outgoing methods.
jfreerails.controller.FinancialDataGatherer.treasuryStock
Javadoc:
/** Returns the number of stock in the Treasury */
Method code:
/** Returns the number of stock in the Treasury */
public int treasuryStock() {
return stockInRRs[playerID];
}
No outgoing methods.
jfreerails.controller.FinancialDataGathererTest.addBond
Javadoc:
/** * Adds a bond and returns true if another bond can be added. Written to * avoid copy & paste in testCanIssueBond(). */
Method code:
/**
* Adds a bond and returns true if another bond can be added. Written to
* avoid copy & paste in testCanIssueBond().
*/
private boolean addBond() {
FinancialDataGatherer fdg;
w.addTransaction(player.getPrincipal(), BondTransaction.issueBond(5));
fdg = new FinancialDataGatherer(w, player.getPrincipal());
boolean canIssueBond = fdg.canIssueBond();
return canIssueBond;
}
Outgoing Methods (calls):
jfreerails.controller.FinancialDataGathererTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
player =new Player("Player X", 0);
w = new WorldImpl();
Move addPlayer = AddPlayerMove.generateMove(w, player);
MoveStatus ms = addPlayer.doMove(w, Player.AUTHORITATIVE);
assertTrue(ms.ok);
}
Outgoing Methods (calls):
jfreerails.controller.FinancialDataGathererTest.testBuyingStakesInOtherRRs
Javadoc:
No Javadoc available
Method code:
public void testBuyingStakesInOtherRRs(){
w = new WorldImpl();
Player[] players = new Player[2];
for(int i = 0; i < players.length; i++){
players[i] = new Player("Player "+i, i);
Move addPlayer = AddPlayerMove.generateMove(w, players[i]);
MoveStatus ms = addPlayer.doMove(w, Player.AUTHORITATIVE);
assertTrue(ms.ok);
}
//Make player #0 buy stock in player #1
int quantity = 10000;
Transaction t = StockTransaction.buyOrSellStock(1, quantity, new Money(5));
w.addTransaction(players[0].getPrincipal(), t);
FinancialDataGatherer fdg = new FinancialDataGatherer(w, players[0].getPrincipal());
assertEquals(0, fdg.treasuryStock());
int actual = fdg.getStockInRRs()[1];
assertEquals(quantity, actual);
}
Outgoing Methods (calls):
jfreerails.controller.FinancialDataGathererTest.testCanIssueBond
Javadoc:
No Javadoc available
Method code:
public void testCanIssueBond() {
FinancialDataGatherer fdg = new FinancialDataGatherer(w, player
.getPrincipal());
assertTrue(fdg.canIssueBond()); // 5%
assertTrue(addBond()); // 6%
assertTrue(addBond()); // 7%
assertFalse(addBond()); // 8% so can't
fdg = new FinancialDataGatherer(w, player.getPrincipal());
assertEquals(8, fdg.nextBondInterestRate());
}
Outgoing Methods (calls):
jfreerails.controller.FinancialDataGathererTest.testNextBondInterestRate
Javadoc:
No Javadoc available
Method code:
public void testNextBondInterestRate() {
FinancialDataGatherer fdg = new FinancialDataGatherer(w, player
.getPrincipal());
assertEquals(5, fdg.nextBondInterestRate());
w.addTransaction(player.getPrincipal(), BondTransaction.issueBond(5));
fdg = new FinancialDataGatherer(w, player.getPrincipal());
assertEquals(6, fdg.nextBondInterestRate());
}
Outgoing Methods (calls):
jfreerails.controller.FinancialDataGathererTest.testTotalShares
Javadoc:
No Javadoc available
Method code:
public void testTotalShares() {
FinancialDataGatherer fdg = new FinancialDataGatherer(w, player
.getPrincipal());
int expected = FinancialMoveProducer.IPO_SIZE;
assertEquals(expected, fdg.totalShares());
}
Outgoing Methods (calls):
jfreerails.controller.FinancialDataGathererTest.testTreasuryStock
Javadoc:
No Javadoc available
Method code:
public void testTreasuryStock() {
FreerailsPrincipal principal = player.getPrincipal();
FinancialDataGatherer fdg = new FinancialDataGatherer(w, principal);
assertEquals(0, fdg.treasuryStock());
int treasuryStock = 10000;
int totalStock = FinancialMoveProducer.IPO_SIZE;
int publicStock = totalStock - treasuryStock;
Transaction t = StockTransaction.buyOrSellStock(0, treasuryStock, new Money(5));
w.addTransaction(principal, t);
fdg = new FinancialDataGatherer(w, principal);
assertEquals(treasuryStock,
fdg.treasuryStock());
assertEquals(totalStock,
fdg.totalShares());
assertEquals(publicStock,
fdg.sharesHeldByPublic());
}
Outgoing Methods (calls):
jfreerails.controller.FinancialMoveProducer.improve
Javadoc:
No Javadoc available
Method code:
EconomicClimate improve() {
return null;
}
No outgoing methods.
jfreerails.controller.FinancialMoveProducer.worsen
Javadoc:
No Javadoc available
Method code:
EconomicClimate worsen() {
return null;
}
No outgoing methods.
jfreerails.controller.FlatTrackExplorer.getEdgeCost
Javadoc:
No Javadoc available
Method code:
public int getEdgeCost() {
return (int) Math.round(currentBranch.cameFrom().getLength());
}
Outgoing Methods (calls):
jfreerails.controller.FlatTrackExplorer.getFirstVectorToTry
Javadoc:
No Javadoc available
Method code:
Step getFirstVectorToTry() {
if (beforeFirst) {
// Return the vector that is 45 degrees clockwise from the opposite
// of the current position.
Step v = this.currentPosition.cameFrom();
v = v.getOpposite();
int i = v.getID();
i++;
i = i % 8;
v = Step.getInstance(i);
return v;
}
// Return the vector that is 45 degrees clockwise from the direction
// of the current branch.
Step v = this.currentBranch.cameFrom();
int i = v.getID();
i++;
i = i % 8;
v = Step.getInstance(i);
return v;
}
Outgoing Methods (calls):
jfreerails.controller.FlatTrackExplorer.getH
Javadoc:
No Javadoc available
Method code:
public int getH() {
// TODO Auto-generated method stub
return 0;
}
No outgoing methods.
jfreerails.controller.FlatTrackExplorer.getPosition
Javadoc:
/** * Returns the integer representation of the current position on the track. * This method delegates to the {@code toInt()} method of the * {@code PositionOnTrack} class to convert the current position to an integer. * * @return the integer value of the current position on the track */
Method code:
public int getPosition() {
return this.currentPosition.toInt();
}
Outgoing Methods (calls):
jfreerails.controller.FlatTrackExplorer.getPossiblePositions
Javadoc:
/** * @return an array of PositionOnTrack objects describing the set of * possible orientations at this position (heading towards the * center of the tile) * @param p * location of track to consider. */
Method code:
/**
* @return an array of PositionOnTrack objects describing the set of
* possible orientations at this position (heading towards the
* center of the tile)
* @param p
* location of track to consider.
*/
public static PositionOnTrack[] getPossiblePositions(ReadOnlyWorld w,
ImPoint p) {
TrackPiece tp = ((FreerailsTile) w.getTile(p.x, p.y)).getTrackPiece();
TrackConfiguration conf = tp.getTrackConfiguration();
Step[] vectors = Step.getList();
// Count the number of possible positions.
int n = 0;
for (int i = 0; i < vectors.length; i++) {
if (conf.contains(vectors[i].get9bitTemplate())) {
n++;
}
}
PositionOnTrack[] possiblePositions = new PositionOnTrack[n];
n = 0;
for (int i = 0; i < vectors.length; i++) {
if (conf.contains(vectors[i].get9bitTemplate())) {
possiblePositions[n] = PositionOnTrack.createComingFrom(p.x,
p.y, vectors[i].getOpposite());
n++;
}
}
return possiblePositions;
}
Outgoing Methods (calls):
jfreerails.controller.FlatTrackExplorer.getVertexConnectedByEdge
Javadoc:
No Javadoc available
Method code:
public int getVertexConnectedByEdge() {
return currentBranch.toInt();
}
Outgoing Methods (calls):
jfreerails.controller.FlatTrackExplorer.getWorld
Javadoc:
No Javadoc available
Method code:
public ReadOnlyWorld getWorld() {
return w;
}
No outgoing methods.
jfreerails.controller.FlatTrackExplorer.hasNextEdge
Javadoc:
No Javadoc available
Method code:
public boolean hasNextEdge() {
if (beforeFirst) {
// We can always go back the way we have come, so if we are before
// the first
// branch, there must be a branch: the one we used to get here.
return true;
}
// Since we can always go back the way we have come, if the direction of
// current branch is not equal to the opposite of the current direction,
// there must be another branch.
Step currentBranchDirection = this.currentBranch.cameFrom();
Step oppositeToCurrentDirection = this.currentPosition.cameFrom()
.getOpposite();
if (oppositeToCurrentDirection.getID() == currentBranchDirection
.getID()) {
return false;
}
return true;
}
Outgoing Methods (calls):
jfreerails.controller.FlatTrackExplorer.moveForward
Javadoc:
No Javadoc available
Method code:
public void moveForward() {
if (beforeFirst) {
throw new IllegalStateException();
}
this.setPosition(this.getVertexConnectedByEdge());
}
Outgoing Methods (calls):
jfreerails.controller.FlatTrackExplorer.nextEdge
Javadoc:
No Javadoc available
Method code:
public void nextEdge() {
if (!hasNextEdge()) {
throw new NoSuchElementException();
}
Step v = this.getFirstVectorToTry();
Point p = new Point(currentPosition.getX(), currentPosition.getY());
FreerailsTile ft = (FreerailsTile)w.getTile(p.x, p.y);
TrackPiece tp = ft.getTrackPiece();
TrackConfiguration conf = tp.getTrackConfiguration();
Step[] vectors = Step.getList();
int i = v.getID();
int loopCounter = 0;
while (!conf.contains(vectors[i].get9bitTemplate())) {
i++;
i = i % 8;
loopCounter++;
if (8 < loopCounter) {
throw new IllegalStateException();
// This should never happen.. ..but it does happen when you
// removed the track from under a train.
}
}
Step branchDirection = Step.getInstance(i);
this.currentBranch.setCameFrom(branchDirection);
int x = this.currentPosition.getX() + branchDirection.deltaX;
int y = this.currentPosition.getY() + branchDirection.deltaY;
this.currentBranch.setX(x);
this.currentBranch.setY(y);
beforeFirst = false;
}
Outgoing Methods (calls):
jfreerails.controller.FlatTrackExplorer.setPosition
Javadoc:
/** * Sets the current position on the track based on the provided integer value. * This method updates the internal position state and resets the {@code beforeFirst} flag to {@code true}, * indicating the start of a new position tracking sequence. * * @param i the integer value representing the track position to set */
Method code:
public void setPosition(int i) {
beforeFirst = true;
currentPosition.setValuesFromInt(i);
}
Outgoing Methods (calls):
jfreerails.controller.FlatTrackExplorerTest.setUp
Javadoc:
/** * Sets up the test environment by initializing a world, adding a test player, * configuring game rules to no restrictions, generating track rule lists, * and creating/validating track piece construction moves. * * This method initializes a {@link jfreerails.world.top.WorldImpl} instance, * adds a test player, sets game rules to {@link ITEM.GAME_RULES} with * {@link GameRules.NO_RESTRICTIONS}, generates track rules via * {@link MapFixtureFactory.generateTrackRuleList}, and constructs * multiple {@link ChangeTrackPieceCompositeMove} instances to build track * pieces. Each move is executed and verified to ensure success. * * @param none * @return void * @throws none */
Method code:
@Override
protected void setUp() {
world = new WorldImpl(20, 20);
world.addPlayer(testPlayer);
world.set(ITEM.GAME_RULES, GameRules.NO_RESTRICTIONS);
MapFixtureFactory.generateTrackRuleList(world);
TrackRule rule = (TrackRule) world.get(SKEY.TRACK_RULES, 0);
Step[] vectors = { Step.WEST, Step.EAST, Step.NORTH_EAST };
ImPoint p = new ImPoint(10, 10);
ImPoint[] points = { p, p, p };
for (int i = 0; i < points.length; i++) {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(points[i], vectors[i], rule, rule,
world, MapFixtureFactory.TEST_PRINCIPAL);
MoveStatus ms = move.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.ok);
}
}
Outgoing Methods (calls):
jfreerails.controller.FlatTrackExplorerTest.testGetFirstVectorToTry
Javadoc:
No Javadoc available
Method code:
public void testGetFirstVectorToTry() {
setUp();
PositionOnTrack p = PositionOnTrack.createComingFrom(10, 10,
Step.SOUTH_WEST);
FlatTrackExplorer fte = new FlatTrackExplorer(world, p);
Step v = fte.getFirstVectorToTry();
assertEquals(Step.EAST, v);
}
Outgoing Methods (calls):
jfreerails.controller.FlatTrackExplorerTest.testGetPossibleDirections
Javadoc:
/** * Tests that the track explorer at point 10,10 tells us that we can move * west, east, or northeast. */
Method code:
/**
* Tests that the track explorer at point 10,10 tells us that we can move
* west, east, or northeast.
*/
public void testGetPossibleDirections() {
setUp();
FlatTrackExplorer fte;
PositionOnTrack p = PositionOnTrack.createComingFrom(10, 10,
Step.SOUTH_WEST);
fte = new FlatTrackExplorer(world, p);
// There should be 3 branches.
assertTrue(fte.hasNextEdge());
fte.nextEdge();
p.setValuesFromInt(fte.getVertexConnectedByEdge());
assertEquals(Step.EAST, p.cameFrom());
assertTrue(fte.hasNextEdge());
fte.nextEdge();
p.setValuesFromInt(fte.getVertexConnectedByEdge());
assertEquals(Step.WEST, p.cameFrom());
assertTrue(fte.hasNextEdge());
fte.nextEdge();
p.setValuesFromInt(fte.getVertexConnectedByEdge());
assertEquals(Step.NORTH_EAST, p.cameFrom());
assertTrue(!fte.hasNextEdge());
}
Outgoing Methods (calls):
jfreerails.controller.FlatTrackExplorerTest.testGetPossiblePositions
Javadoc:
No Javadoc available
Method code:
public void testGetPossiblePositions() {
setUp();
PositionOnTrack[] positions = FlatTrackExplorer.getPossiblePositions(
world, new ImPoint(10, 10));
assertNotNull(positions);
assertEquals(3, positions.length);
HashSet<Step> directions = new HashSet<Step>();
directions.add(Step.WEST);
directions.add(Step.EAST);
directions.add(Step.SOUTH_WEST);
HashSet<Step> directions2 = new HashSet<Step>();
for (int i = 0; i < positions.length; i++) {
directions2.add(positions[i].cameFrom());
}
assertEquals(directions, directions2);
}
Outgoing Methods (calls):
jfreerails.controller.FlatTrackExplorerTest.testHasNext
Javadoc:
No Javadoc available
Method code:
public void testHasNext() {
setUp();
FlatTrackExplorer explorer = new FlatTrackExplorer(world,
PositionOnTrack.createComingFrom(10, 10, Step.EAST));
assertTrue(explorer.hasNextEdge());
}
Outgoing Methods (calls):
jfreerails.controller.FlatTrackExplorerTest.testMoveTrackExplorer
Javadoc:
/** * Tests that we can move the track explorer at point 10,10 northeast, and * that when we have done this, we can move it back again. */
Method code:
/**
* Tests that we can move the track explorer at point 10,10 northeast, and
* that when we have done this, we can move it back again.
*/
public void testMoveTrackExplorer() {
setUp();
FlatTrackExplorer fte;
PositionOnTrack p = PositionOnTrack.createComingFrom(10, 10, Step.EAST);
fte = new FlatTrackExplorer(world, p);
PositionOnTrack pos = new PositionOnTrack(fte.getPosition());
assertEquals(10, pos.getX());
assertEquals(10, pos.getY());
assertTrue(fte.hasNextEdge());
fte.nextEdge();
pos.setValuesFromInt(fte.getVertexConnectedByEdge());
assertEquals(Step.NORTH_EAST, pos.cameFrom());
assertEquals(11, pos.getX());
assertEquals(9, pos.getY());
int branchPosition = fte.getVertexConnectedByEdge();
fte.moveForward();
assertEquals(branchPosition, fte.getPosition());
pos.setValuesFromInt(fte.getPosition());
assertEquals(11, pos.getX());
assertEquals(9, pos.getY());
assertTrue(fte.hasNextEdge());
fte.nextEdge();
assertEquals(Step.SOUTH_WEST, fte.currentBranch.cameFrom());
assertTrue(!fte.hasNextEdge());
fte.moveForward();
pos.setValuesFromInt(fte.getPosition());
assertEquals(10, pos.getX());
assertEquals(10, pos.getY());
}
Outgoing Methods (calls):
jfreerails.controller.GraphExplorer.getEdgeCost
Javadoc:
/** Returns the cost of the current edge. */
Method code:
/** Returns the cost of the current edge. */
int getEdgeCost();
No outgoing methods.
jfreerails.controller.GraphExplorer.getH
Javadoc:
/** * Returns the value of H associated with the current node or element in the graph exploration. * The 'H' value represents a specific attribute or metric used during graph traversal or analysis. * * @return the integer value of H */
Method code:
int getH();
No outgoing methods.
jfreerails.controller.GraphExplorer.getPosition
Javadoc:
/** Return the current edge. */
Method code:
/** Return the current edge. */
int getPosition();
No outgoing methods.
jfreerails.controller.GraphExplorer.getVertexConnectedByEdge
Javadoc:
/** * Returns the vertex that is connected to the current vertex by the current * edge. */
Method code:
/**
* Returns the vertex that is connected to the current vertex by the current
* edge.
*/
int getVertexConnectedByEdge();
No outgoing methods.
jfreerails.controller.GraphExplorer.hasNextEdge
Javadoc:
No Javadoc available
Method code:
boolean hasNextEdge();
No outgoing methods.
jfreerails.controller.GraphExplorer.moveForward
Javadoc:
/** * Moves this GraphExplorer from the current vertex to the vertex that is * connected to the current vertex by the current edge. */
Method code:
/**
* Moves this GraphExplorer from the current vertex to the vertex that is
* connected to the current vertex by the current edge.
*/
void moveForward();
No outgoing methods.
jfreerails.controller.GraphExplorer.nextEdge
Javadoc:
/** * Sets the current edge to the current vertex's next edge. Throws a * NoSuchElementException if the vertex does not have another edge. */
Method code:
/**
* Sets the current edge to the current vertex's next edge. Throws a
* NoSuchElementException if the vertex does not have another edge.
*/
void nextEdge();
No outgoing methods.
jfreerails.controller.GraphExplorer.setPosition
Javadoc:
No Javadoc available
Method code:
void setPosition(int vertex);
No outgoing methods.
jfreerails.controller.IncrementalPathFinder.abandonSearch
Javadoc:
No Javadoc available
Method code:
public abstract void abandonSearch();
No outgoing methods.
jfreerails.controller.IncrementalPathFinder.getStatus
Javadoc:
No Javadoc available
Method code:
public abstract int getStatus();
No outgoing methods.
jfreerails.controller.JFrameMinimumSizeEnforcer.componentHidden
Javadoc:
No Javadoc available
Method code:
public void componentHidden(ComponentEvent arg0) {
}
No outgoing methods.
jfreerails.controller.JFrameMinimumSizeEnforcer.componentMoved
Javadoc:
No Javadoc available
Method code:
public void componentMoved(ComponentEvent arg0) {
}
No outgoing methods.
jfreerails.controller.JFrameMinimumSizeEnforcer.componentResized
Javadoc:
No Javadoc available
Method code:
public void componentResized(ComponentEvent arg0) {
Component c = arg0.getComponent();
int width = c.getWidth();
int height = c.getHeight();
// we check if either the width
// or the height are below minimum
boolean resize = false;
if (width < minWidth) {
resize = true;
width = minWidth;
}
if (height < minHeight) {
resize = true;
height = minHeight;
}
if (resize) {
c.setSize(width, height);
}
}
No outgoing methods.
jfreerails.controller.JFrameMinimumSizeEnforcer.componentShown
Javadoc:
No Javadoc available
Method code:
public void componentShown(ComponentEvent arg0) {
}
No outgoing methods.
jfreerails.controller.Map.getEdgeCost
Javadoc:
No Javadoc available
Method code:
public int getEdgeCost() {
return nodes[position].distances[branch];
}
No outgoing methods.
jfreerails.controller.Map.getH
Javadoc:
No Javadoc available
Method code:
public int getH() {
// TODO Auto-generated method stub
return 0;
}
No outgoing methods.
jfreerails.controller.Map.getPosition
Javadoc:
No Javadoc available
Method code:
public int getPosition() {
return this.position;
}
No outgoing methods.
jfreerails.controller.Map.getVertexConnectedByEdge
Javadoc:
No Javadoc available
Method code:
public int getVertexConnectedByEdge() {
return nodes[position].edges[branch];
}
No outgoing methods.
jfreerails.controller.Map.hasNextEdge
Javadoc:
No Javadoc available
Method code:
public boolean hasNextEdge() {
if (nodes[position].edges.length > (branch + 1)) {
return true;
}
return false;
}
No outgoing methods.
jfreerails.controller.Map.moveForward
Javadoc:
/** * Moves the entity forward by updating its position to the vertex connected by the current edge. * This method retrieves the connected vertex using {@link #getVertexConnectedByEdge()} and sets it as the new position via {@link #setPosition(Object)}. */
Method code:
public void moveForward() {
this.setPosition(this.getVertexConnectedByEdge());
}
Outgoing Methods (calls):
jfreerails.controller.Map.nextEdge
Javadoc:
No Javadoc available
Method code:
public void nextEdge() {
if (hasNextEdge()) {
branch++;
} else {
throw new NoSuchElementException();
}
}
Outgoing Methods (calls):
jfreerails.controller.Map.setPosition
Javadoc:
/** * Sets the position of the map to the specified integer value and resets the branch to -1. * * @param i the new position value to set */
Method code:
public void setPosition(int i) {
this.position = i;
this.branch = -1;
}
No outgoing methods.
jfreerails.controller.Message2Client.execute
Javadoc:
/** Executes this command on the specified ClientControlInterface. */
Method code:
/** Executes this command on the specified ClientControlInterface. */
MessageStatus execute(ClientControlInterface client);
No outgoing methods.
jfreerails.controller.Message2Client.getID
Javadoc:
/** Returns the id of this command. */
Method code:
/** Returns the id of this command. */
int getID();
No outgoing methods.
jfreerails.controller.Message2Server.execute
Javadoc:
No Javadoc available
Method code:
MessageStatus execute(ServerControlInterface server);
No outgoing methods.
jfreerails.controller.Message2Server.getID
Javadoc:
No Javadoc available
Method code:
int getID();
No outgoing methods.
jfreerails.controller.MessageStatus.getId
Javadoc:
/** Returns the id of the command whose status this object stores. */
Method code:
/** Returns the id of the command whose status this object stores. */
public int getId() {
return id;
}
No outgoing methods.
jfreerails.controller.MessageStatus.getReason
Javadoc:
/** Returns the reason the command failed, may be null. */
Method code:
/** Returns the reason the command failed, may be null. */
public String getReason() {
return reason;
}
No outgoing methods.
jfreerails.controller.MessageStatus.isSuccessful
Javadoc:
/** True if the command was successfully executed. */
Method code:
/** True if the command was successfully executed. */
public boolean isSuccessful() {
return successful;
}
No outgoing methods.
jfreerails.controller.ModelRoot.getProperty
Javadoc:
No Javadoc available
Method code:
Object getProperty(Property property);
No outgoing methods.
jfreerails.controller.ModelRoot.is
Javadoc:
/** * Tests whether the specified property has the specified value. */
Method code:
/**
* Tests whether the specified property has the specified value.
*/
boolean is(Property property, Object value);
No outgoing methods.
jfreerails.controller.ModelRoot.sendCommand
Javadoc:
No Javadoc available
Method code:
void sendCommand(Message2Server c);
No outgoing methods.
jfreerails.controller.ModelRoot.setProperty
Javadoc:
No Javadoc available
Method code:
void setProperty(Property property, Object newValue);
No outgoing methods.
jfreerails.controller.MoveExecutor.doMove
Javadoc:
No Javadoc available
Method code:
MoveStatus doMove(Move m);
No outgoing methods.
jfreerails.controller.MoveExecutor.doPreMove
Javadoc:
No Javadoc available
Method code:
MoveStatus doPreMove(PreMove pm);
No outgoing methods.
jfreerails.controller.MoveExecutor.getPrincipal
Javadoc:
No Javadoc available
Method code:
FreerailsPrincipal getPrincipal();
No outgoing methods.
jfreerails.controller.MoveExecutor.getWorld
Javadoc:
No Javadoc available
Method code:
ReadOnlyWorld getWorld();
No outgoing methods.
jfreerails.controller.MoveExecutor.tryDoMove
Javadoc:
No Javadoc available
Method code:
MoveStatus tryDoMove(Move m);
No outgoing methods.
jfreerails.controller.MoveTrainPreMove.acceleration
Javadoc:
No Javadoc available
Method code:
double acceleration(int wagons) {
return 0.5d/(wagons + 1);
}
No outgoing methods.
jfreerails.controller.MoveTrainPreMove.currentTrainTarget
Javadoc:
No Javadoc available
Method code:
private ImPoint currentTrainTarget(ReadOnlyWorld w) {
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
return ta.getTarget();
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove.findNextStep
Javadoc:
/** Uses static method to make testing easier.*/
Method code:
/** Uses static method to make testing easier.*/
public static Step findNextStep(ReadOnlyWorld world,
PositionOnTrack currentPosition, ImPoint target) {
PathOnTrackFinder pathFinder = new PathOnTrackFinder(world);
try {
ImPoint location = new ImPoint(currentPosition.getX(),
currentPosition.getY());
pathFinder.setupSearch(location, target);
pathFinder.search(-1);
return pathFinder.pathAsVectors()[0];
} catch (PathNotFoundException e) {
// The pathfinder couldn't find a path so we
// go in any legal direction.
FlatTrackExplorer explorer = new FlatTrackExplorer(world,
currentPosition);
explorer.nextEdge();
int next = explorer.getVertexConnectedByEdge();
PositionOnTrack nextPosition = new PositionOnTrack(next);
return nextPosition.cameFrom();
}
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove.generateMove
Javadoc:
No Javadoc available
Method code:
public Move generateMove(ReadOnlyWorld w) {
// Check that we can generate a move.
if (!isUpdateDue(w))
throw new IllegalStateException();
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
TrainMotion tm = ta.findCurrentMotion(Double.MAX_VALUE);
SpeedTimeAndStatus.TrainActivity activity = tm.getActivity();
switch (activity) {
case STOPPED_AT_STATION:
return moveTrain(w);
case READY:
{
// Are we at a station?
TrainStopsHandler stopsHandler = new TrainStopsHandler(trainID,
principal, new WorldDiffs(w));
ta.getStationId(Integer.MAX_VALUE);
PositionOnTrack pot = tm.getFinalPosition();
int x = pot.getX();
int y = pot.getY();
boolean atStation = stopsHandler.getStationID(x, y) >= 0;
TrainMotion nextMotion;
if (atStation) {
// We have just arrived at a station.
double durationOfStationStop = 10;
stopsHandler.arrivesAtPoint(x, y);
SpeedTimeAndStatus.TrainActivity status = stopsHandler.isWaiting4FullLoad() ? WAITING_FOR_FULL_LOAD : STOPPED_AT_STATION;
PathOnTiles path = tm.getPath();
int lastTrainLength = tm.getTrainLength();
int currentTrainLength = stopsHandler.getTrainLength();
//If we are adding wagons we may need to lengthen the path.
if(lastTrainLength < currentTrainLength){
path = TrainStopsHandler.lengthenPath(w, path, currentTrainLength);
}
nextMotion = new TrainMotion(path, currentTrainLength,
durationOfStationStop, status);
// Create a new Move object.
Move trainMove = new NextActivityMove(nextMotion, trainID,
principal);
Move cargoMove = stopsHandler.getMoves();
return new CompositeMove(trainMove, cargoMove);
}
return moveTrain(w);
}
case WAITING_FOR_FULL_LOAD:
{
TrainStopsHandler stopsHandler = new TrainStopsHandler(trainID,
principal, new WorldDiffs(w));
boolean waiting4fullLoad = stopsHandler.refreshWaitingForFullLoad();
Move cargoMove = stopsHandler.getMoves();
if(!waiting4fullLoad){
Move trainMove = moveTrain(w);
if(null != trainMove){
return new CompositeMove(trainMove, cargoMove);
}else{
return cargoMove;
}
}
stopsHandler.makeTrainWait(30);
return cargoMove;
}
default:
throw new UnsupportedOperationException(activity.toString());
}
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove.getActivity
Javadoc:
No Javadoc available
Method code:
public SpeedTimeAndStatus.TrainActivity getActivity(ReadOnlyWorld w){
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
TrainMotion tm = ta.findCurrentMotion(Integer.MAX_VALUE);
return tm.getActivity();
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove.isUpdateDue
Javadoc:
/** * Returns true iff an updated is due. * */
Method code:
/**
* Returns true iff an updated is due.
*
*/
public boolean isUpdateDue(ReadOnlyWorld w) {
GameTime currentTime = w.currentTime();
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
ActivityIterator ai = w.getActivities(principal, trainID);
ai.gotoLastActivity();
double finishTime = ai.getFinishTime();
double ticks = currentTime.getTicks();
boolean hasFinishedLastActivity = Math.floor(finishTime) <= ticks;
TrainActivity trainActivity = ta.getStatus(finishTime);
if(trainActivity == TrainActivity.WAITING_FOR_FULL_LOAD){
//Check whether there is any cargo that can be added to the train.
ImInts spaceAvailable = ta.spaceAvailable();
int stationId = ta.getStationId(ticks);
if(stationId == -1)
throw new IllegalStateException();
StationModel station = (StationModel)w.get(principal, KEY.STATIONS, stationId);
CargoBundle cb = (CargoBundle)w.get(principal, KEY.CARGO_BUNDLES, station.getCargoBundleID());
for(int i = 0; i < spaceAvailable.size(); i++){
int space = spaceAvailable.get(i);
int atStation = cb.getAmount(i);
if(space * atStation > 0){
logger.fine("There is cargo to transfer!");
return true;
}
}
return !ta.keepWaiting();
}
return hasFinishedLastActivity;
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove.lastMotion
Javadoc:
No Javadoc available
Method code:
private TrainMotion lastMotion(ReadOnlyWorld w) {
ActivityIterator ai = w.getActivities(principal, trainID);
ai.gotoLastActivity();
TrainMotion lastMotion = (TrainMotion) ai.getActivity();
return lastMotion;
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove.moveTrain
Javadoc:
No Javadoc available
Method code:
private Move moveTrain(ReadOnlyWorld w) {
// Find the next vector.
Step nextVector = nextStep(w);
HashMap<TrackSection, Integer> occupiedTrackSections = occupiedTrackSections(w);
TrainMotion motion = lastMotion(w);
PositionOnTrack pot = motion.getFinalPosition();
ImPoint tile = new ImPoint(pot.getX(), pot.getY());
TrackSection desiredTrackSection = new TrackSection(nextVector, tile);
// Check whether the desired track section is single or double track.
ImPoint tileA = desiredTrackSection.tileA();
ImPoint tileB = desiredTrackSection.tileB();
FreerailsTile fta = (FreerailsTile) w.getTile(tileA.x, tileA.y);
FreerailsTile ftb = (FreerailsTile) w.getTile(tileB.x, tileB.y);
TrackPiece tpa = fta.getTrackPiece();
TrackPiece tpb = ftb.getTrackPiece();
int tracks = 1;
if (tpa.getTrackRule().isDouble() && tpb.getTrackRule().isDouble()) {
tracks = 2;
}
if (occupiedTrackSections.containsKey(desiredTrackSection)) {
int trains = occupiedTrackSections.get(desiredTrackSection);
if (trains >= tracks) {
// We need to wait for the track ahead to clear.
return stopTrain(w);
}
}
// Create a new train motion object.
TrainMotion nextMotion = nextMotion(w, nextVector);
return new NextActivityMove(nextMotion, trainID, principal);
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove.nextMotion
Javadoc:
No Javadoc available
Method code:
TrainMotion nextMotion(ReadOnlyWorld w, Step v) {
TrainMotion motion = lastMotion(w);
SpeedAgainstTime speeds = nextSpeeds(w, v);
PathOnTiles currentTiles = motion.getTiles(motion.duration());
PathOnTiles pathOnTiles = currentTiles.addSteps(v);
return new TrainMotion(pathOnTiles, currentTiles.steps(), motion
.getTrainLength(), speeds);
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove.nextSpeeds
Javadoc:
No Javadoc available
Method code:
SpeedAgainstTime nextSpeeds(ReadOnlyWorld w, Step v) {
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
TrainMotion lastMotion = lastMotion(w);
double u = lastMotion.getSpeedAtEnd();
double s = v.getLength();
int wagons = ta.getTrain().getNumberOfWagons();
double a0 = acceleration(wagons);
double topSpeed = topSpeed(wagons);
SpeedAgainstTime newSpeeds;
if (u < topSpeed) {
double t = (topSpeed - u) / a0;
SpeedAgainstTime a = ConstAcc.uat(u, a0, t);
t = s / topSpeed + 1; // Slightly overestimate the time
SpeedAgainstTime b = ConstAcc.uat(topSpeed, 0, t);
newSpeeds = new CompositeSpeedAgainstTime(a, b);
} else {
double t;
t = s / topSpeed + 1; // Slightly overestimate the time
newSpeeds = ConstAcc.uat(topSpeed, 0, t);
}
return newSpeeds;
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove.nextStep
Javadoc:
No Javadoc available
Method code:
Step nextStep(ReadOnlyWorld w) {
// Find current position.
TrainMotion currentMotion = lastMotion(w);
PositionOnTrack currentPosition = currentMotion.getFinalPosition();
// Find targets
ImPoint targetPoint = currentTrainTarget(w);
return findNextStep(w, currentPosition, targetPoint);
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove.occupiedTrackSections
Javadoc:
No Javadoc available
Method code:
private HashMap<TrackSection, Integer> occupiedTrackSections(ReadOnlyWorld w) {
HashMap<TrackSection, Integer> occupiedTrackSections = new HashMap<TrackSection, Integer>();
for (int i = 0; i < w.size(principal, KEY.TRAINS); i++) {
TrainModel train = (TrainModel) w.get(principal,
KEY.TRAINS, i);
if (null == train)
continue;
TrainAccessor ta = new TrainAccessor(w, principal, i);
GameTime gt = w.currentTime();
if(ta.isMoving(gt.getTicks())){
HashSet<TrackSection> sections = ta.occupiedTrackSection(gt.getTicks());
for (TrackSection section : sections) {
if(occupiedTrackSections.containsKey(section)){
int count = occupiedTrackSections.get(section);
count++;
occupiedTrackSections.put(section, count);
}else{
occupiedTrackSections.put(section, 1);
}
}
}
}
return occupiedTrackSections;
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove.stopTrain
Javadoc:
No Javadoc available
Method code:
public Move stopTrain(ReadOnlyWorld w) {
TrainMotion motion = lastMotion(w);
SpeedAgainstTime stopped = ConstAcc.STOPPED;
double duration = motion.duration();
int trainLength = motion.getTrainLength();
PathOnTiles tiles = motion.getTiles(duration);
int engineDist = tiles.steps();
TrainMotion nextMotion = new TrainMotion(tiles, engineDist,
trainLength, stopped);
return new NextActivityMove(nextMotion, trainID, principal);
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove.topSpeed
Javadoc:
No Javadoc available
Method code:
double topSpeed(int wagons) {
return 10 / (wagons + 1);
}
No outgoing methods.
jfreerails.controller.MoveTrainPreMove1stTest.setupLoopOfTrack
Javadoc:
No Javadoc available
Method code:
private void setupLoopOfTrack() {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
TrackMoveProducer producer = new TrackMoveProducer(me, world, mr);
Step[] trackPath = { EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, WEST,
NORTH_WEST, NORTH, NORTH_EAST };
ImPoint from = new ImPoint(5, 5);
MoveStatus ms = producer.buildTrack(from, trackPath);
assertTrue(ms.ok);
TrainOrdersModel[] orders = {};
ImmutableSchedule is = new ImmutableSchedule(orders, -1, false);
AddTrainPreMove addTrain = new AddTrainPreMove(0, new ImInts(), from,
principal, is);
Move m = addTrain.generateMove(world);
ms = m.doMove(world, principal);
assertTrue(ms.ok);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
TrainMotion motion = ta.findCurrentMotion(0);
assertNotNull(motion);
PathOnTiles expected = new PathOnTiles(from, SOUTH_WEST);
PathOnTiles actual = motion.getTiles(motion.duration());
assertEquals(expected, actual);
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove1stTest.setupWorld
Javadoc:
/** * Sets up the test world by initializing the map, building tracks and stations, * configuring train orders, and preparing a pre-move action for a train. * This method creates a terminal station at position (10,10), another station at (19,10), * and configures a train with specific orders. It also verifies that all operations succeed. * * @throws Exception If any step in the setup fails, though assertions ensure success. */
Method code:
@Override
protected void setupWorld() {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
trackBuilder = new TrackMoveProducer(me, world, mr);
stationBuilder = new StationBuilder(me);
// Build track.
stationBuilder
.setStationType(stationBuilder.getTrackTypeID("terminal"));
Step[] track = { EAST, EAST, EAST, EAST, EAST, EAST, EAST, EAST, EAST };
stationA = new ImPoint(10, 10);
MoveStatus ms0 = trackBuilder.buildTrack(stationA, track);
assertTrue(ms0.ok);
// Build 2 stations.
MoveStatus ms1 = stationBuilder.buildStation(stationA);
assertTrue(ms1.ok);
stationB = new ImPoint(19, 10);
MoveStatus ms2 = stationBuilder.buildStation(stationB);
assertTrue(ms2.ok);
TrainOrdersModel order0 = new TrainOrdersModel(1, null, false, false);
TrainOrdersModel order1 = new TrainOrdersModel(0, null, false, false);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
defaultSchedule = s.toImmutableSchedule();
ImPoint start = new ImPoint(10, 10);
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0),
start, principal, defaultSchedule);
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, principal);
assertTrue(ms.ok);
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove1stTest.testFindNextVector
Javadoc:
No Javadoc available
Method code:
public void testFindNextVector() {
setupLoopOfTrack();
PositionOnTrack pot = PositionOnTrack.createFacing(4, 6, SOUTH_WEST);
ImPoint target = new ImPoint();
Step expected = NORTH_EAST;
assertEquals(expected, MoveTrainPreMove.findNextStep(world, pot,
target));
pot.move(expected);
expected = EAST;
assertEquals(expected, MoveTrainPreMove.findNextStep(world, pot,
target));
pot.move(expected);
expected = SOUTH_EAST;
assertEquals(expected, MoveTrainPreMove.findNextStep(world, pot,
target));
pot.move(expected);
expected = SOUTH;
assertEquals(expected, MoveTrainPreMove.findNextStep(world, pot,
target));
pot.move(expected);
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove1stTest.testGetTiles
Javadoc:
No Javadoc available
Method code:
public void testGetTiles() {
setupLoopOfTrack();
MoveTrainPreMove moveTrain = new MoveTrainPreMove(0, principal);
Move m = moveTrain.generateMove(world);
assertTrue(m.doMove(world, principal).ok);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
TrainMotion motion = ta.findCurrentMotion(1);
double duration = motion.duration();
assertTrue(duration > 1);
int trainLength = motion.getTrainLength();
for (int i = 0; i < 10; i++) {
double t = i == 0 ? 0 : duration * i / 10;
PathOnTiles tiles = motion.getTiles(t);
assertTrue("t=" + t, tiles.steps() > 0);
assertTrue("t=" + t, tiles.getTotalDistance() >= trainLength);
}
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove1stTest.testMove
Javadoc:
No Javadoc available
Method code:
@Override
public void testMove() {
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
Move m = preMove.generateMove(world);
assertNotNull(m);
assertSurvivesSerialisation(m);
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove1stTest.testMove2
Javadoc:
No Javadoc available
Method code:
public void testMove2() {
MoveStatus ms;
Move m;
setupLoopOfTrack();
TrainAccessor ta = new TrainAccessor(world, principal, 0);
TrainMotion tm = ta.findCurrentMotion(3);
assertEquals(0d, tm.duration());
PathOnTiles expected = new PathOnTiles(new ImPoint(5, 5), SOUTH_WEST);
assertEquals(expected, tm.getPath());
PositionOnTrack pot = tm.getFinalPosition();
int x = pot.getX();
assertEquals(4, x);
int y = pot.getY();
assertEquals(6, y);
assertEquals(SOUTH_WEST, pot.facing());
MoveTrainPreMove moveTrain = new MoveTrainPreMove(0, principal);
assertEquals(NORTH_EAST, moveTrain.nextStep(world));
m = moveTrain.generateMove(world);
ms = m.doMove(world, principal);
assertTrue(ms.ok);
TrainMotion tm2 = ta.findCurrentMotion(3);
assertFalse(tm.equals(tm2));
expected = new PathOnTiles(new ImPoint(5, 5), SOUTH_WEST, NORTH_EAST);
assertEquals(expected, tm2.getPath());
assertTrue(tm2.duration() > 3d);
// The expected value is 3.481641930846211, found from
// stepping thu code in debugger.
assertTrackHere(tm2.getTiles(tm2.duration()));
pot = tm2.getFinalPosition();
assertEquals(4, x);
assertEquals(6, y);
// assertEquals(SOUTH, pot.facing());
assertTrackHere(x, y);
assertEquals(EAST, moveTrain.nextStep(world));
MoveTrainPreMove2ndTest.incrTime(world, principal);
m = moveTrain.generateMove(world);
ms = m.doMove(world, principal);
assertTrue(ms.ok);
TrainMotion tm3 = ta.findCurrentMotion(100);
assertFalse(tm3.equals(tm2));
expected = new PathOnTiles(new ImPoint(4, 6), NORTH_EAST, EAST);
assertEquals(expected, tm3.getPath());
assertTrackHere(tm3.getTiles(tm3.duration()));
assertTrackHere(tm3.getTiles(tm3.duration() / 2));
assertTrackHere(tm3.getTiles(0));
assertTrackHere(tm3.getPath());
assertEquals(SOUTH_EAST, moveTrain.nextStep(world));
MoveTrainPreMove2ndTest.incrTime(world, principal);
m = moveTrain.generateMove(world);
ms = m.doMove(world, principal);
assertTrue(ms.ok);
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove1stTest.testMovingRoundLoop
Javadoc:
No Javadoc available
Method code:
public void testMovingRoundLoop() {
setupLoopOfTrack();
MoveTrainPreMove moveTrain = new MoveTrainPreMove(0, principal);
Move m = moveTrain.generateMove(world);
assertTrue(m.doMove(world, principal).ok);
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove1stTest.testNextSpeeds
Javadoc:
No Javadoc available
Method code:
public void testNextSpeeds() {
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
SpeedAgainstTime speeds = preMove.nextSpeeds(world, EAST);
assertNotNull(speeds);
assertEquals(speeds.calcV(0), 0d);
assertTrue(speeds.getS() >= EAST.getLength());
double t = speeds.getT();
assertTrue(t > 0);
assertTrue(speeds.calcV(t) > 0);
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove1stTest.testNextVector
Javadoc:
No Javadoc available
Method code:
public void testNextVector() {
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
Step actual = preMove.nextStep(world);
assertNotNull(actual);
// The train is at station A, so should head east to station B.
assertEquals(EAST, actual);
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove2ndTest.addCargoAtStation
Javadoc:
/** Adds the specified amount of cargo #0 to the specified station. */
Method code:
/** Adds the specified amount of cargo #0 to the specified station. */
private void addCargoAtStation(int stationId, int amount) {
CargoBatch cb = new CargoBatch(0, 6, 6, 0, stationId);
MutableCargoBundle mb = new MutableCargoBundle();
mb.addCargo(cb, amount);
StationModel station1Model = (StationModel) world.get(principal, KEY.STATIONS, stationId);
ImmutableCargoBundle cargoAtStationBefore = mb.toImmutableCargoBundle();
int station1BundleId = station1Model.getCargoBundleID();
world.set(principal, KEY.CARGO_BUNDLES, station1BundleId, cargoAtStationBefore);
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove2ndTest.ignoreTestAutoConsist
Javadoc:
/** Tests that a train with 'select wagons automatically' enable behaves correctly.*/
Method code:
/** Tests that a train with 'select wagons automatically' enable behaves correctly.*/
public void ignoreTestAutoConsist(){
TrainAccessor ta = new TrainAccessor(world, principal, 0);
//Remove all wagons from the train.
TrainModel model = ta.getTrain();
model = model.getNewInstance(model.getEngineType(), new ImInts());
world.set(principal, KEY.TRAINS, 0, model);
//Change trains schedule to auto consist.
TrainOrdersModel order0 = new TrainOrdersModel(1, null, false, true);
TrainOrdersModel order1 = new TrainOrdersModel(2, null, false, true);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
world.set(principal, KEY.TRAIN_SCHEDULES, 0, s.toImmutableSchedule());
assertEquals(0, ta.getSchedule().getOrderToGoto());
//Add 35 unit of cargo #0 to station 1.
StationModel station0 = (StationModel)world.get(principal, KEY.STATIONS, 1);
int cargoBundleId = station0.getCargoBundleID();
MutableCargoBundle mcb = new MutableCargoBundle();
final int AMOUNT_OF_CARGO = 35;
mcb.addCargo(new CargoBatch(0, 0,0, 0, 0), AMOUNT_OF_CARGO);
world.set(principal, KEY.CARGO_BUNDLES, cargoBundleId, mcb.toImmutableCargoBundle());
//Make station2 demand cargo #0;
boolean[] boolArray = new boolean[world.size(SKEY.CARGO_TYPES)];
boolArray[0] = true;
Demand4Cargo demand = new Demand4Cargo(boolArray);
StationModel station2 = (StationModel)world.get(principal, KEY.STATIONS, 2);
StationModel stationWithNewDemand = new StationModel(station2, demand);
world.set(principal, KEY.STATIONS, 2, stationWithNewDemand);
//The train should be bound for station 1.
assertEquals(1, ta.getSchedule().getStationToGoto());
//Make train call at station 1.
PositionOnTrack pot;
TrainMotion tm;
do {
tm = moveTrain();
pot = tm.getFinalPosition();
} while (pot.getX() < station1Location.x);
assertEquals(station1Location.x, pot.getX());
assertEquals(station1Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
tm = moveTrain();
pot = tm.getFinalPosition();
//The train should be bound for station 2.
assertEquals(2, ta.getSchedule().getStationToGoto());
//Check that the train has picked up the cargo.
//The train should have one wagon of type #0
assertEquals(new ImInts(0), ta.getTrain().getConsist());
assertEquals(AMOUNT_OF_CARGO, ta.getCargoBundle().getAmount(0));
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove2ndTest.incrTime
Javadoc:
No Javadoc available
Method code:
static void incrTime(World w, FreerailsPrincipal p) {
ActivityIterator ai = w.getActivities(p, 0);
while (ai.hasNext())
ai.nextActivity();
double finishTime = ai.getFinishTime();
GameTime newTime = new GameTime((int) Math.floor(finishTime));
w.setTime(newTime);
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove2ndTest.moveTrain
Javadoc:
No Javadoc available
Method code:
private TrainMotion moveTrain() {
incrTime(world, principal);
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, principal);
assertTrue(ms.message, ms.ok);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
TrainMotion tm = ta.findCurrentMotion(Integer.MAX_VALUE);
return tm;
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove2ndTest.nextStep
Javadoc:
No Javadoc available
Method code:
private Step nextStep() {
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
Step step = preMove.nextStep(world);
return step;
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove2ndTest.putTrainAtStationWaiting4FullLoad
Javadoc:
No Javadoc available
Method code:
private void putTrainAtStationWaiting4FullLoad() {
// Set wait until full on schedule.
ImInts newConsist = new ImInts(0, 0);
TrainOrdersModel order0 = new TrainOrdersModel(2, newConsist, true, false);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
MutableSchedule schedule = new MutableSchedule(ta.getSchedule());
schedule.setOrder(0, order0);
ImmutableSchedule imSchedule = schedule.toImmutableSchedule();
world.set(principal, KEY.TRAIN_SCHEDULES, 0, imSchedule);
assertEquals(0, ta.getSchedule().getOrderToGoto());
assertTrue(ta.getSchedule().getOrder(0).waitUntilFull);
// Add some cargo to station #2, but not enough to fill the train.
addCargoAtStation(2, 20);
// Move the train to just before station 2.
PositionOnTrack pot;
TrainMotion tm;
do {
tm = moveTrain();
pot = tm.getFinalPosition();
} while (pot.getX() < station2Location.x);
assertEquals(station2Location.x, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
// The train should now stop at the station
// and wait for a full load.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station2Location.y, pot.getY());
assertEquals(WAITING_FOR_FULL_LOAD, tm.getActivity());
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
assertFalse("The train isn't full and there is no cargo to add, so we should be able to generate a move.", preMove.isUpdateDue(world));
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove2ndTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
/** <ol>
* <li>Obtains a map from MapFixtureFactory2</li>
* <li>Builds a track from (10,10) to (30, 10).</li>
* <li>Builds stations at (10,10), (20, 10), and (28,10).</li>
* <li>Builds a train with two wagons of type #0 and places it at (10, 10)</li>
* <li>Schedules the train to move between stations 0 and 2 without changing consist</li>
* </ol>
*/
protected void setUp() throws Exception {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
trackBuilder = new TrackMoveProducer(me, world, mr);
stationBuilder = new StationBuilder(me);
// Build track.
stationBuilder.setStationType(stationBuilder.getTrackTypeID("terminal"));
Step[] track = new Step[20];
for (int i = 0; i < track.length; i++) {
track[i] = EAST;
}
station0Location = new ImPoint(10, 10);
MoveStatus ms0 = trackBuilder.buildTrack(station0Location, track);
assertTrue(ms0.ok);
// Build 2 stations.
MoveStatus ms1 = stationBuilder.buildStation(station0Location);
assertTrue(ms1.ok);
station1Location = new ImPoint(20, 10);
MoveStatus ms2 = stationBuilder.buildStation(station1Location);
assertTrue(ms2.ok);
station2Location = new ImPoint(28, 10);
MoveStatus ms3 = stationBuilder.buildStation(station2Location);
assertTrue(ms3.ok);
TrainOrdersModel order0 = new TrainOrdersModel(2, null, false, false);
TrainOrdersModel order1 = new TrainOrdersModel(0, null, false, false);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
defaultSchedule = s.toImmutableSchedule();
ImPoint start = new ImPoint(10, 10);
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0), start, principal,
defaultSchedule);
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, principal);
assertTrue(ms.ok);
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove2ndTest.testCanGenerateMove
Javadoc:
No Javadoc available
Method code:
public void testCanGenerateMove() {
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
assertTrue(preMove.isUpdateDue(world));
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, principal);
assertTrue(ms.message, ms.ok);
assertFalse(preMove.isUpdateDue(world));
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove2ndTest.testLengtheningTrain
Javadoc:
/** * Tests that when extra wagons are added, the TrainMotion lengthens to * accommodate them. */
Method code:
/**
* Tests that when extra wagons are added, the TrainMotion lengthens to
* accommodate them.
*/
public void testLengtheningTrain() {
// Set the train to add wagons at station2.
ImInts newConsist = new ImInts(0, 0, 0, 0, 0, 0);
TrainOrdersModel order0 = new TrainOrdersModel(2, newConsist, false, false);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
MutableSchedule schedule = new MutableSchedule(ta.getSchedule());
schedule.setOrder(0, order0);
ImmutableSchedule imSchedule = schedule.toImmutableSchedule();
world.set(principal, KEY.TRAIN_SCHEDULES, 0, imSchedule);
assertEquals(0, ta.getSchedule().getOrderToGoto());
// Move the train to the station.
PositionOnTrack pot;
TrainMotion tm;
do {
tm = moveTrain();
pot = tm.getFinalPosition();
} while (pot.getX() < station2Location.x);
assertEquals(station2Location.x, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
TrainModel train = ta.getTrain();
assertEquals(2, train.getNumberOfWagons());
assertTrue(tm.getInitialPosition() >= train.getLength());
tm = moveTrain();
tm = moveTrain();
train = ta.getTrain();
assertEquals(6, ta.getTrain().getNumberOfWagons());
assertTrue(tm.getInitialPosition() >= train.getLength());
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove2ndTest.testPathFinding
Javadoc:
No Javadoc available
Method code:
public void testPathFinding() {
// setTargetAsStation2();
Step step = nextStep();
assertEquals(EAST, step);
moveTrain();
assertEquals(EAST, nextStep());
moveTrain();
assertEquals(EAST, nextStep());
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove2ndTest.testStops1
Javadoc:
/** Test that when the train arrives at a non station tile it keeps moving. */
Method code:
/** Test that when the train arrives at a non station tile it keeps moving. */
public void testStops1() {
for (int i = 0; i < 5; i++) {
TrainMotion tm = moveTrain();
PositionOnTrack pot = tm.getFinalPosition();
assertEquals(14 + i, pot.getX());
assertEquals(READY, tm.getActivity());
assertTrue(tm.getSpeedAtEnd() > 0);
}
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove2ndTest.testStops2
Javadoc:
/** * Test that when the train arrives at a non scheduled station tile it stops, * drops off and picks up cargo, then continues */
Method code:
/**
* Test that when the train arrives at a non scheduled station tile it stops,
* drops off and picks up cargo, then continues
*/
public void testStops2() {
// Check that there two stations on the schedule: station0 and station2;
TrainAccessor ta = new TrainAccessor(world, principal, 0);
ImmutableSchedule schedule = ta.getSchedule();
assertEquals(2, schedule.getNumOrders());
assertEquals(2, schedule.getOrder(0).getStationID());
// Check the train should have 2 wagons for cargo #0
ImInts expectedConsist = new ImInts(0, 0);
ImInts actualConsist = ta.getTrain().getConsist();
assertEquals(expectedConsist, actualConsist);
addCargoAtStation(1, 800);
// Move the train to just before station 1.
PositionOnTrack pot;
TrainMotion tm;
do {
tm = moveTrain();
pot = tm.getFinalPosition();
} while (pot.getX() < station1Location.x);
assertEquals(station1Location.x, pot.getX());
assertEquals(station1Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
// The next train motion should represent the stop at the station.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station1Location.x, pot.getX());
assertEquals(station1Location.y, pot.getY());
assertEquals(STOPPED_AT_STATION, tm.getActivity());
// 80 Units of cargo should have been transferred to the train!
CargoBundle onTrain = ta.getCargoBundle();
int amount = onTrain.getAmount(0);
assertEquals(80, amount);
// Then the train should continue.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station1Location.x + 1, pot.getX());
assertEquals(station1Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove2ndTest.testStops3
Javadoc:
/** * Test that when the train arrives at a scheduled station tile it stops, * updates its schedule and transfers cargo and starts moving again. */
Method code:
/**
* Test that when the train arrives at a scheduled station tile it stops,
* updates its schedule and transfers cargo and starts moving again.
*/
public void testStops3() {
// Add cargo to station 2
addCargoAtStation(2, 800);
// Keep moving train until it reaches station 2
PositionOnTrack pot;
TrainMotion tm;
int x;
do {
tm = moveTrain();
pot = tm.getFinalPosition();
x = pot.getX();
} while (x < station2Location.x);
assertEquals(station2Location.x, x);
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
// The train should be heading for station 1.
TrainAccessor ta = new TrainAccessor(world, principal, 0);
Schedule schedule1 = ta.getSchedule();
assertEquals(0, schedule1.getOrderToGoto());
assertEquals(2, schedule1.getStationToGoto());
ImPoint expectedTarget = new ImPoint(station2Location.x, station2Location.y);
assertEquals(expectedTarget, ta.getTarget());
// The next train motion should represent the stop at the station.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station2Location.x, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(STOPPED_AT_STATION, tm.getActivity());
// The train should be heading for station 0.
Schedule schedule2 = ta.getSchedule();
assertFalse(schedule2.equals(schedule1));
assertEquals(1, schedule2.getOrderToGoto());
assertEquals(0, schedule2.getStationToGoto());
// 80 Units of cargo should have been transferred to the train!
CargoBundle onTrain = ta.getCargoBundle();
int amount = onTrain.getAmount(0);
assertEquals(80, amount);
// Then the train should continue.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station2Location.x - 1, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove2ndTest.testStops5
Javadoc:
/** * Test that when the train <b>is</b> scheduled to wait for full load, it * waits. */
Method code:
/**
* Test that when the train <b>is</b> scheduled to wait for full load, it
* waits.
*/
public void testStops5() {
PositionOnTrack pot;
TrainMotion tm;
putTrainAtStationWaiting4FullLoad();
// Add enough cargo to fill up the train.
addCargoAtStation(2, 70);
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station2Location.x - 1, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove2ndTest.testStops6
Javadoc:
/** Test that a waiting train whose orders change behaves correctly. */
Method code:
/** Test that a waiting train whose orders change behaves correctly. */
public void testStops6() {
PositionOnTrack pot;
TrainMotion tm;
putTrainAtStationWaiting4FullLoad();
// Now change the train's orders.
ImInts newConsist = new ImInts(0, 0);
TrainOrdersModel order0 = new TrainOrdersModel(2, newConsist, false, false);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
MutableSchedule schedule = new MutableSchedule(ta.getSchedule());
schedule.setOrder(0, order0);
ImmutableSchedule imSchedule = schedule.toImmutableSchedule();
world.set(principal, KEY.TRAIN_SCHEDULES, 0, imSchedule);
assertEquals(0, ta.getSchedule().getOrderToGoto());
assertFalse(ta.getSchedule().getOrder(0).waitUntilFull);
// Then the train should continue.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station2Location.x - 1, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove3rdTest.findPath2Target
Javadoc:
No Javadoc available
Method code:
private void findPath2Target(ImPoint target1, Step[] expectedPath) {
FreerailsTile tile = (FreerailsTile)world.getTile(target1.x, target1.y);
assertTrue(tile.hasTrack());
PositionOnTrack pot = PositionOnTrack.createFacing(10, 10, EAST);
for (int i = 0; i < expectedPath.length; i++) {
Step expected = expectedPath[i];
Step actual = MoveTrainPreMove.findNextStep(world,pot, target1);
assertEquals(String.valueOf(i), expected, actual);
pot.move(expected);
}
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove3rdTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
trackBuilder = new TrackMoveProducer(me, world, mr);
stationBuilder = new StationBuilder(me);
// Build track.
stationBuilder
.setStationType(stationBuilder.getTrackTypeID("terminal"));
stationA = new ImPoint(10, 10);
MoveStatus ms0 = trackBuilder.buildTrack(stationA, line1);
assertTrue(ms0.ok);
ms0 = trackBuilder.buildTrack(stationA, line2);
assertTrue(ms0.ok);
ms0 = trackBuilder.buildTrack(stationA, line3);
assertTrue(ms0.ok);
}
Outgoing Methods (calls):
jfreerails.controller.MoveTrainPreMove3rdTest.testFindingPath
Javadoc:
No Javadoc available
Method code:
public void testFindingPath(){
findPath2Target(new ImPoint(14, 7), line1);
findPath2Target(new ImPoint(9, 13), line2);
findPath2Target(new ImPoint(9, 13), line2);
}
Outgoing Methods (calls):
jfreerails.controller.NetWorthCalculator.condition
Javadoc:
No Javadoc available
Method code:
@Override
protected boolean condition(int transactionID) {
Transaction t = super.w.getTransaction(super.principal,
transactionID);
if (t instanceof AddItemTransaction) {
if(t.getCategory().equals(Transaction.Category.ISSUE_STOCK)){
return true;
}
// Since buying something is just converting one asset type to
// another.
return false;
}
return true;
}
Outgoing Methods (calls):
jfreerails.controller.OpenList.add
Javadoc:
No Javadoc available
Method code:
void add(int node, int f) {
if (map.containsKey(node)) {
OpenListEntry old = map.get(node);
queue.remove(old);
map.remove(node);
}
OpenList.OpenListEntry entry = new OpenListEntry(f, node);
queue.offer(entry);
map.put(node, entry);
}
No outgoing methods.
jfreerails.controller.OpenList.clear
Javadoc:
No Javadoc available
Method code:
void clear() {
queue.clear();
map.clear();
}
No outgoing methods.
jfreerails.controller.OpenList.contains
Javadoc:
No Javadoc available
Method code:
boolean contains(int node) {
boolean containsKey = map.containsKey(node);
return containsKey;
}
No outgoing methods.
jfreerails.controller.OpenList.getF
Javadoc:
No Javadoc available
Method code:
int getF(int node) {
int f = map.get(node).f;
return f;
}
No outgoing methods.
jfreerails.controller.OpenList.popNodeWithSmallestF
Javadoc:
No Javadoc available
Method code:
int popNodeWithSmallestF() {
OpenListEntry entry = queue.remove();
int node = entry.node;
OpenListEntry removed = map.remove(node);
if (null == removed) {
System.out.println("Shizer, size =" + queue.size());
}
return node;
}
No outgoing methods.
jfreerails.controller.OpenList.size
Javadoc:
No Javadoc available
Method code:
int size() {
return queue.size();
}
No outgoing methods.
jfreerails.controller.OpenList.smallestF
Javadoc:
No Javadoc available
Method code:
int smallestF() {
OpenListEntry entry = queue.peek();
return entry.f;
}
No outgoing methods.
jfreerails.controller.OpenListEntry.compareTo
Javadoc:
No Javadoc available
Method code:
public int compareTo(OpenListEntry o) {
// XXX Work around for JDK Bug ID: 6207984
if (f == o.f) {
return node - o.node;
}
return f - o.f;
}
No outgoing methods.
jfreerails.controller.OpenListTest.testAdd
Javadoc:
No Javadoc available
Method code:
public void testAdd() {
OpenList openList = new OpenList();
openList.add(1, 4);
assertEquals(1, openList.size());
assertEquals(4, openList.smallestF());
openList.add(1, 6);
assertEquals(1, openList.size());
assertEquals(6, openList.smallestF());
}
Outgoing Methods (calls):
jfreerails.controller.OpenListTest.testContains
Javadoc:
No Javadoc available
Method code:
public void testContains() {
OpenList openList = new OpenList();
assertFalse(openList.contains(0));
openList.add(0, 4);
assertTrue(openList.contains(0));
assertFalse(openList.contains(4));
openList.popNodeWithSmallestF();
assertFalse(openList.contains(0));
}
Outgoing Methods (calls):
jfreerails.controller.OpenListTest.testGetF
Javadoc:
/** * Tests the functionality of the getF method to ensure it behaves as expected. * This method is part of the test suite for the OpenList class and verifies * the correctness of the getF operation under standard conditions. */
Method code:
public void testGetF() {
}
No outgoing methods.
jfreerails.controller.OpenListTest.testSize
Javadoc:
No Javadoc available
Method code:
public void testSize() {
OpenList openList = new OpenList();
assertEquals(0, openList.size());
openList.add(0, 4);
assertEquals(1, openList.size());
openList.popNodeWithSmallestF();
assertEquals(0, openList.size());
}
Outgoing Methods (calls):
jfreerails.controller.OpenListTest.testSmallestF
Javadoc:
No Javadoc available
Method code:
public void testSmallestF() {
OpenList openList = new OpenList();
openList.add(0, 4);
assertEquals(4, openList.smallestF());
openList.add(1, 5);
assertEquals(4, openList.smallestF());
openList.add(5, 1);
assertEquals(1, openList.smallestF());
openList.popNodeWithSmallestF();
assertEquals(4, openList.smallestF());
openList.popNodeWithSmallestF();
assertEquals(5, openList.smallestF());
}
Outgoing Methods (calls):
jfreerails.controller.PathOnTrackFinder.abandonSearch
Javadoc:
No Javadoc available
Method code:
public void abandonSearch() {
pathFinder.abandonSearch();
}
Outgoing Methods (calls):
jfreerails.controller.PathOnTrackFinder.getStatus
Javadoc:
No Javadoc available
Method code:
public int getStatus() {
return pathFinder.getStatus();
}
Outgoing Methods (calls):
jfreerails.controller.PathOnTrackFinder.pathAsVectors
Javadoc:
No Javadoc available
Method code:
public Step[] pathAsVectors() {
int[] pathAsInts = pathFinder.retrievePath().toArray();
Step[] vectors = new Step[pathAsInts.length];
int x = startPoint.x;
int y = startPoint.y;
for (int i = 0; i < pathAsInts.length; i++) {
PositionOnTrack p2 = new PositionOnTrack(pathAsInts[i]);
vectors[i] = Step.getInstance(p2.getX() - x, p2.getY() - y);
x = p2.getX();
y = p2.getY();
}
return vectors;
}
Outgoing Methods (calls):
jfreerails.controller.PathOnTrackFinder.setupSearch
Javadoc:
No Javadoc available
Method code:
public void setupSearch(ImPoint from, ImPoint target) throws PathNotFoundException {
startPoint = from;
logger
.fine("Find track path from " + from + " to "
+ target);
/* Check there is track at both the points. */
FreerailsTile tileA = (FreerailsTile) world.getTile(from.x,
from.y);
FreerailsTile tileB = (FreerailsTile) world.getTile(target.x,
target.y);
if (!tileA.hasTrack()) {
throw new PathNotFoundException("No track at " + from.x
+ ", " + from.y + ".");
}
if (!tileB.hasTrack()) {
throw new PathNotFoundException("No track at " + target.x
+ ", " + target.y + ".");
}
PositionOnTrack[] startPoints = FlatTrackExplorer.getPossiblePositions(
world, from);
PositionOnTrack[] targetPoints = FlatTrackExplorer
.getPossiblePositions(world, target);
FlatTrackExplorer explorer = new FlatTrackExplorer(world,
startPoints[0]);
pathFinder.setupSearch(PositionOnTrack.toInts(startPoints),
PositionOnTrack.toInts(targetPoints), explorer);
}
Outgoing Methods (calls):
jfreerails.controller.PathOnTrackFinderTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
super.setUp();
w = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(w, 0);
ModelRoot mr = new ModelRootImpl();
producer = new TrackMoveProducer(me, w, mr);
pathFinder = new PathOnTrackFinder(w);
stationBuilder = new StationBuilder(me);
bts = BuildTrackStrategy.getDefault(w);
}
Outgoing Methods (calls):
jfreerails.controller.PathOnTrackFinderTest.tearDown
Javadoc:
No Javadoc available
Method code:
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
No outgoing methods.
jfreerails.controller.PathOnTrackFinderTest.testPathAsVectors1
Javadoc:
No Javadoc available
Method code:
public void testPathAsVectors1() {
Step[] path = { EAST, EAST, SOUTH_EAST };
ImPoint start = new ImPoint(5, 5);
ImPoint end = Step.move(start, path);
producer.buildTrack(start, path);
try {
pathFinder.setupSearch(start, end);
pathFinder.search(-1);
assertEquals(IncrementalPathFinder.PATH_FOUND, pathFinder
.getStatus());
Step[] pathFound = pathFinder.pathAsVectors();
assertTrue(Arrays.equals(path, pathFound));
} catch (PathNotFoundException e) {
fail();
}
}
Outgoing Methods (calls):
jfreerails.controller.PathOnTrackFinderTest.testPathAsVectors2
Javadoc:
/** * Tests the pathAsVectors method to ensure it returns the correct path when a valid path is found. * This test sets up a predefined path, calculates the end point, builds the track, and verifies * that the search finds the path and the returned vectors match the expected steps. */
Method code:
public void testPathAsVectors2() {
Step[] path = { EAST, EAST, SOUTH_EAST, EAST, EAST, NORTH_EAST };
ImPoint start = new ImPoint(5, 5);
ImPoint end = Step.move(start, path);
producer.buildTrack(start, path);
try {
pathFinder.setupSearch(start, end);
pathFinder.search(-1);
assertEquals(IncrementalPathFinder.PATH_FOUND, pathFinder
.getStatus());
Step[] pathFound = pathFinder.pathAsVectors();
assertTrue(Arrays.equals(path, pathFound));
} catch (PathNotFoundException e) {
fail();
}
}
Outgoing Methods (calls):
jfreerails.controller.PathOnTrackFinderTest.testSetupSearch
Javadoc:
No Javadoc available
Method code:
public void testSetupSearch() {
Step[] path = { EAST, EAST, SOUTH_EAST };
ImPoint start = new ImPoint(5, 5);
ImPoint end = Step.move(start, path);
producer.buildTrack(start, path);
try {
pathFinder.setupSearch(start, end);
} catch (PathNotFoundException e) {
fail("Track at both of the points so no exception should be thrown");
}
try {
pathFinder.setupSearch(start, new ImPoint(10, 10));
fail("No track at one of the points so an exception should be thrown");
} catch (PathNotFoundException e) {
}
try {
pathFinder.setupSearch(new ImPoint(10, 10), end);
fail("No track at one of the points so an exception should be thrown");
} catch (PathNotFoundException e) {
}
}
Outgoing Methods (calls):
jfreerails.controller.PreMove.generateMove
Javadoc:
No Javadoc available
Method code:
Move generateMove(ReadOnlyWorld w);
No outgoing methods.
jfreerails.controller.PreMoveStatus.failed
Javadoc:
No Javadoc available
Method code:
public static PreMoveStatus failed(String reason) {
return new PreMoveStatus(MoveStatus.moveFailed(reason));
}
Outgoing Methods (calls):
jfreerails.controller.PreMoveStatus.fromMoveStatus
Javadoc:
No Javadoc available
Method code:
public static PreMoveStatus fromMoveStatus(MoveStatus ms) {
if (ms.ok) {
return PRE_MOVE_OK;
}
return new PreMoveStatus(ms);
}
No outgoing methods.
jfreerails.controller.PreMoveStatus.readResolve
Javadoc:
/** * Avoid creating a duplicate when deserializing. */
Method code:
/**
* Avoid creating a duplicate when deserializing.
*/
private Object readResolve() {
if (ms.ok) {
return PRE_MOVE_OK;
}
return this;
}
No outgoing methods.
jfreerails.controller.ProcessCargoAtStationMoveGenerator.processCargo
Javadoc:
No Javadoc available
Method code:
public static ArrayList<Move> processCargo(ReadOnlyWorld w,
CargoBundle bundle, int stationID, FreerailsPrincipal p,
int trainId) {
StationModel thisStation = (StationModel) w.get(p,
KEY.STATIONS, stationID);
Iterator<CargoBatch> batches = bundle.cargoBatchIterator();
ArrayList<Move> moves = new ArrayList<Move>();
while (batches.hasNext()) {
CargoBatch batch = batches.next();
double distanceSquared = (batch.getSourceX() - thisStation.x)
* (batch.getSourceX() - thisStation.x)
+ (batch.getSourceY() - thisStation.y)
* (batch.getSourceY() - thisStation.y);
double dist = Math.sqrt(distanceSquared);
int quantity = bundle.getAmount(batch);
double amount = quantity * Math.log(dist) * MAGIC_NUMBER;
Money money = new Money((long) amount);
DeliverCargoReceipt receipt = new DeliverCargoReceipt(money,
quantity, stationID, batch, trainId);
moves.add(new AddTransactionMove(p, receipt));
}
return moves;
}
Outgoing Methods (calls):
jfreerails.controller.RandomPathFinder.hasNext
Javadoc:
No Javadoc available
Method code:
public boolean hasNext() {
return trackExplorer.hasNextEdge();
}
Outgoing Methods (calls):
jfreerails.controller.RandomPathFinder.nextSegment
Javadoc:
No Javadoc available
Method code:
public void nextSegment(IntLine line) {
p1.setValuesFromInt(trackExplorer.getPosition());
line.x1 = p1.getX() * tileSize + tileSize / 2;
line.y1 = p1.getY() * tileSize + tileSize / 2;
trackExplorer.nextEdge();
trackExplorer.moveForward();
p2.setValuesFromInt(trackExplorer.getPosition());
line.x2 = p2.getX() * tileSize + tileSize / 2;
line.y2 = p2.getY() * tileSize + tileSize / 2;
}
Outgoing Methods (calls):
jfreerails.controller.ReportBugTextGenerator.appendBuildProps
Javadoc:
No Javadoc available
Method code:
private static void appendBuildProps(StringBuffer sb) {
String version = null;
String builtBy = null;;
try {
Properties props = new Properties();
InputStream in = ReportBugTextGenerator.class
.getResourceAsStream("/build.properties");
props.load(in);
in.close();
version = props.getProperty("freerails.build");
builtBy = props.getProperty("freerails.built.by");
} catch (Exception e) {
// ignore, there's nothing useful we can do.
}
version = null == version ? "not set" : version;
builtBy = null == builtBy ? "not set" : builtBy;
sb.append("\t");
sb.append(System.getProperty("os.name"));
sb.append(" ");
sb.append(System.getProperty("os.version"));
sb.append("\n\t");
sb.append(System.getProperty("java.vm.name"));
sb.append(" ");
sb.append(System.getProperty("java.version"));
sb.append("\n\t");
sb.append("Freerails build ");
sb.append(version);
sb.append(" compiled by ");
sb.append(builtBy);
}
No outgoing methods.
jfreerails.controller.ReportBugTextGenerator.genException
Javadoc:
No Javadoc available
Method code:
private static Exception genException() {
Exception e = new Exception();
return e;
}
No outgoing methods.
jfreerails.controller.ReportBugTextGenerator.genText
Javadoc:
No Javadoc available
Method code:
public static String genText(Exception e) {
StackTraceElement[] s = e.getStackTrace();
StringBuffer sb = new StringBuffer();
sb.append("Unexpected Exception\n");
sb.append("\n");
sb.append("Consider submitting a bug report using the sourceforge.net" +
" bug tracker at the following url:\n");
sb.append(TRACKER_URL);
sb.append("\n");
sb.append("\n");
sb.append("Please:\n");
sb.append(" 1. Use the following as the title of the bug report:\n\t");
sb.append(" Unexpected Exception: ");
sb.append(s[0].getFileName());
sb.append(" line ");
sb.append(s[0].getLineNumber());
sb.append("\n");
sb.append(" 2. Include steps to reproduce the bug (attach a save game if appropriate).\n");
sb.append(" 3. Copy and paste the details below into the bug report:\n");
appendBuildProps(sb);
sb.append("\n");
sb.append("\n\t");
sb.append(e.toString());
for (StackTraceElement ste : s) {
sb.append("\n\t\t at ");
sb.append(ste);
}
return sb.toString();
}
Outgoing Methods (calls):
jfreerails.controller.ReportBugTextGenerator.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
Exception e = genException();
System.out.println(genText());
System.out.println(genText(e));
}
Outgoing Methods (calls):
jfreerails.controller.ReportBugTextGenerator.unexpectedException
Javadoc:
No Javadoc available
Method code:
@SuppressWarnings("deprecation")
public static void unexpectedException(Exception e) {
ScreenHandler.exitFullScreenMode();
String str = genText(e);
System.err.print(str);
UnexpectedExceptionForm unexpectedExceptionForm = new UnexpectedExceptionForm();
unexpectedExceptionForm.setText(str);
unexpectedExceptionForm.setVisible(true);
if(!EventQueue.isDispatchThread()){
Thread.currentThread().stop();
}
}
Outgoing Methods (calls):
jfreerails.controller.ScreenHandler.apply
Javadoc:
No Javadoc available
Method code:
public synchronized void apply() {
switch (mode) {
case FULL_SCREEN: {
goFullScreen(frame, displayMode);
break;
}
case WINDOWED_MODE: {
// Some of the dialogue boxes do not get layed out properly if they
// are smaller than their
// minimum size. JFrameMinimumSizeEnforcer increases the size of the
// Jframe when its size falls
// below the specified size.
frame.addComponentListener(new JFrameMinimumSizeEnforcer(640, 480));
frame.setSize(640, 480);
frame.setVisible(true);
break;
}
case FIXED_SIZE_WINDOWED_MODE: {
/*
* We need to make the frame not displayable before calling
* setUndecorated(true) otherwise a
* java.awt.IllegalComponentStateException will get thrown.
*/
if (frame.isDisplayable()) {
frame.dispose();
}
frame.setUndecorated(true);
frame.setResizable(false);
frame.setSize(640, 480);
frame.setVisible(true);
break;
}
default:
throw new IllegalArgumentException(String.valueOf(mode));
}
createBufferStrategy();
frame.addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(java.awt.event.ComponentEvent evt) {
createBufferStrategy();
}
});
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowIconified(WindowEvent e) {
isMinimised = true;
}
@Override
public void windowDeiconified(WindowEvent e) {
isMinimised = false;
}
});
isInUse = true;
}
Outgoing Methods (calls):
jfreerails.controller.ScreenHandler.contentsRestored
Javadoc:
No Javadoc available
Method code:
public boolean contentsRestored() {
return bufferStrategy.contentsRestored();
}
No outgoing methods.
jfreerails.controller.ScreenHandler.createBufferStrategy
Javadoc:
No Javadoc available
Method code:
private synchronized void createBufferStrategy() {
// Use 2 backbuffers to avoid using too much VRAM.
frame.createBufferStrategy(2);
bufferStrategy = frame.getBufferStrategy();
setRepaintOffAndDisableDoubleBuffering(frame);
}
Outgoing Methods (calls):
jfreerails.controller.ScreenHandler.exitFullScreenMode
Javadoc:
No Javadoc available
Method code:
public synchronized static void exitFullScreenMode(){
device.setFullScreenWindow(null);
}
No outgoing methods.
jfreerails.controller.ScreenHandler.getBestDisplayMode
Javadoc:
No Javadoc available
Method code:
private static DisplayMode getBestDisplayMode() {
for (int x = 0; x < BEST_DISPLAY_MODES.length; x++) {
DisplayMode[] modes = device.getDisplayModes();
for (int i = 0; i < modes.length; i++) {
if (modes[i].getWidth() == BEST_DISPLAY_MODES[x].getWidth()
&& modes[i].getHeight() == BEST_DISPLAY_MODES[x]
.getHeight()
&& modes[i].getBitDepth() == BEST_DISPLAY_MODES[x]
.getBitDepth()) {
logger.fine("Best display mode is "
+ (new MyDisplayMode(BEST_DISPLAY_MODES[x]))
.toString());
return BEST_DISPLAY_MODES[x];
}
}
}
return null;
}
Outgoing Methods (calls):
jfreerails.controller.ScreenHandler.getDrawGraphics
Javadoc:
No Javadoc available
Method code:
public synchronized Graphics getDrawGraphics() {
return bufferStrategy.getDrawGraphics();
}
No outgoing methods.
jfreerails.controller.ScreenHandler.goFullScreen
Javadoc:
No Javadoc available
Method code:
private static void goFullScreen(JFrame frame, DisplayMode displayMode) {
setRepaintOffAndDisableDoubleBuffering(frame);
/*
* We need to make the frame not displayable before calling
* setUndecorated(true) otherwise a
* java.awt.IllegalComponentStateException will get thrown.
*/
if (frame.isDisplayable()) {
frame.dispose();
}
frame.setUndecorated(true);
device.setFullScreenWindow(frame);
if (device.isDisplayChangeSupported()) {
if (null == displayMode) {
displayMode = getBestDisplayMode();
}
logger.info("Setting display mode to: "
+ (new MyDisplayMode(displayMode).toString()));
device.setDisplayMode(displayMode);
}
frame.validate();
}
Outgoing Methods (calls):
jfreerails.controller.ScreenHandler.isInUse
Javadoc:
No Javadoc available
Method code:
public synchronized boolean isInUse() {
return isInUse;
}
No outgoing methods.
jfreerails.controller.ScreenHandler.isMinimised
Javadoc:
No Javadoc available
Method code:
public synchronized boolean isMinimised() {
return isMinimised;
}
No outgoing methods.
jfreerails.controller.ScreenHandler.setRepaintOffAndDisableDoubleBuffering
Javadoc:
No Javadoc available
Method code:
private static void setRepaintOffAndDisableDoubleBuffering(Component c) {
c.setIgnoreRepaint(true);
// Since we are using a buffer strategy we don't want Swing
// to double buffer any JComponents.
if (c instanceof JComponent) {
JComponent jComponent = (JComponent) c;
jComponent.setDoubleBuffered(false);
}
if (c instanceof java.awt.Container) {
Component[] children = ((Container) c).getComponents();
for (int i = 0; i < children.length; i++) {
setRepaintOffAndDisableDoubleBuffering(children[i]);
}
}
}
Outgoing Methods (calls):
jfreerails.controller.ScreenHandler.swapScreens
Javadoc:
No Javadoc available
Method code:
public synchronized void swapScreens() {
if (!bufferStrategy.contentsLost()) {
bufferStrategy.show();
}
}
No outgoing methods.
jfreerails.controller.ServerControlInterface.loadgame
Javadoc:
No Javadoc available
Method code:
void loadgame(String saveGameName) throws IOException;
No outgoing methods.
jfreerails.controller.ServerControlInterface.newGame
Javadoc:
No Javadoc available
Method code:
void newGame(String mapName);
No outgoing methods.
jfreerails.controller.ServerControlInterface.refreshSavedGames
Javadoc:
No Javadoc available
Method code:
void refreshSavedGames();
No outgoing methods.
jfreerails.controller.ServerControlInterface.savegame
Javadoc:
No Javadoc available
Method code:
void savegame(String saveGameName);
No outgoing methods.
jfreerails.controller.ServerControlInterface.stopGame
Javadoc:
No Javadoc available
Method code:
void stopGame();
No outgoing methods.
jfreerails.controller.SharePriceCalculator.calculatePrice
Javadoc:
No Javadoc available
Method code:
public long calculatePrice() {
assert totalShares > 0;
assert totalShares >= treasuryStock + otherRRStakes;
assert stockholderEquity > 0;
long price;
long currentValue = networth + stockholderEquity;
long expectedIncrease = profitsLastYear * 5;
int publicOwnedShares = totalShares - treasuryStock - otherRRStakes;
price = 2 * (currentValue + expectedIncrease)
/ (2 * publicOwnedShares + otherRRStakes);
return price;
}
No outgoing methods.
jfreerails.controller.SharePriceCalculatorTest.test1
Javadoc:
No Javadoc available
Method code:
public void test1() {
SharePriceCalculator cal = new SharePriceCalculator();
cal.networth = 100000;
cal.profitsLastYear = 100000;
cal.stockholderEquity = 500000;
cal.totalShares = 100000;
long expected = (100000 + 500000 + 100000 * 5) / 100000;
assertEquals(expected, cal.calculatePrice());
}
Outgoing Methods (calls):
jfreerails.controller.SimpleAStarPathFinder.abandonSearch
Javadoc:
No Javadoc available
Method code:
public void abandonSearch() {
path = new IntArray();
searchStartTime = 0;
bestPath = PATH_NOT_FOUND;
bestPathF = Integer.MAX_VALUE;
// initialize the open list
openList.clear();
// initialize the closed list
closedList.clear();
shortestPath.clear();
startingPositions.clear();
status = SEARCH_NOT_STARTED;
}
Outgoing Methods (calls):
jfreerails.controller.SimpleAStarPathFinder.findpath
Javadoc:
No Javadoc available
Method code:
public IntArray findpath(int[] currentPosition, int[] targets,
GraphExplorer e) throws PathNotFoundException {
logger.fine(currentPosition.length + " starting points; "
+ targets.length + " targets.");
setupSearch(currentPosition, targets, e);
search(-1);
return path;
}
Outgoing Methods (calls):
jfreerails.controller.SimpleAStarPathFinder.findstep
Javadoc:
No Javadoc available
Method code:
public int findstep(int currentPosition, int[] targets,
GraphExplorer tempExplorer) {
try {
return findpath(new int[] { currentPosition }, targets,
tempExplorer).get(0);
} catch (PathNotFoundException e) {
return PATH_NOT_FOUND;
}
}
Outgoing Methods (calls):
jfreerails.controller.SimpleAStarPathFinder.getStatus
Javadoc:
No Javadoc available
Method code:
public int getStatus() {
return status;
}
No outgoing methods.
jfreerails.controller.SimpleAStarPathFinder.retrievePath
Javadoc:
No Javadoc available
Method code:
public IntArray retrievePath() {
return path;
}
No outgoing methods.
jfreerails.controller.SimpleAStarPathFinder.setupSearch
Javadoc:
No Javadoc available
Method code:
public void setupSearch(int[] currentPosition, int[] targets,
GraphExplorer e) throws PathNotFoundException {
abandonSearch();
explorer = e;
// put the starting nodes on the open list (you can leave its f at zero)
for (int i = 0; i < targets.length; i++) {
openList.add(targets[i], 0);
for (int j = 0; j < currentPosition.length; j++) {
if (targets[i] == currentPosition[j]) {
status = PATH_NOT_FOUND;
throw new PathNotFoundException("Already at target!");
}
}
}
for (int j = 0; j < currentPosition.length; j++) {
startingPositions.add(currentPosition[j]);
}
}
Outgoing Methods (calls):
jfreerails.controller.SimpleAStarPathFinderTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() {
this.map = new Map();
pathFinder = new SimpleAStarPathFinder();
}
No outgoing methods.
jfreerails.controller.SimpleAStarPathFinderTest.testExplorer
Javadoc:
No Javadoc available
Method code:
public void testExplorer() {
setUp();
assertEquals(0, map.getPosition());
assertTrue(map.hasNextEdge());
map.nextEdge();
assertTrue(!map.hasNextEdge());
assertEquals(1, map.getVertexConnectedByEdge());
assertEquals(11, map.getEdgeCost());
map.moveForward();
assertEquals(1, map.getPosition());
assertTrue(map.hasNextEdge());
map.nextEdge();
assertEquals(0, map.getVertexConnectedByEdge());
// now try jumping to a different position.
map.setPosition(2);
assertEquals(2, map.getPosition());
assertTrue(map.hasNextEdge());
map.nextEdge();
assertEquals(5, map.getVertexConnectedByEdge());
}
Outgoing Methods (calls):
jfreerails.controller.SimpleAStarPathFinderTest.testFindpath
Javadoc:
No Javadoc available
Method code:
public void testFindpath() {
setUp();
int i = pathFinder.findstep(0, new int[] { 1 }, map);
assertEquals(1, i);
i = pathFinder.findstep(0, new int[] { 5 }, map);
assertEquals(1, i);
i = pathFinder.findstep(0, new int[] { 4 }, map);
assertEquals(1, i);
i = pathFinder.findstep(5, new int[] { 7 }, map);
assertEquals(6, i);
i = pathFinder.findstep(4, new int[] { 1 }, map);
assertEquals(2, i);
i = pathFinder.findstep(5, new int[] { 0, 7 }, map);
assertEquals(6, i);
i = pathFinder.findstep(5, new int[] { 4 }, map);
assertEquals(2, i);
i = pathFinder.findstep(4, new int[] { 4 }, map);
assertEquals(IncrementalPathFinder.PATH_NOT_FOUND, i);
i = pathFinder.findstep(2, new int[] { 1 }, map);
assertEquals(1, i);
}
Outgoing Methods (calls):
jfreerails.controller.SimpleMoveExecutor.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(Move m) {
return m.doMove(w, p);
}
Outgoing Methods (calls):
jfreerails.controller.SimpleMoveExecutor.doPreMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doPreMove(PreMove pm) {
Move m = pm.generateMove(w);
return m.doMove(w, p);
}
Outgoing Methods (calls):
jfreerails.controller.SimpleMoveExecutor.getPrincipal
Javadoc:
No Javadoc available
Method code:
public FreerailsPrincipal getPrincipal() {
return p;
}
No outgoing methods.
jfreerails.controller.SimpleMoveExecutor.getWorld
Javadoc:
No Javadoc available
Method code:
public ReadOnlyWorld getWorld() {
return w;
}
No outgoing methods.
jfreerails.controller.SimpleMoveExecutor.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(Move m) {
return m.tryDoMove(w, p);
}
Outgoing Methods (calls):
jfreerails.controller.StationBuilder.buildStation
Javadoc:
No Javadoc available
Method code:
public MoveStatus buildStation(ImPoint p) {
// Only build a station if there is track at the specified point.
MoveStatus status = tryBuildingStation(p);
if (status.ok) {
FreerailsPrincipal principal = executor.getPrincipal();
AddStationPreMove preMove = AddStationPreMove.newStation(p,
this.ruleNumber, principal);
return executor.doPreMove(preMove);
}
logger.fine(status.message);
return status;
}
Outgoing Methods (calls):
jfreerails.controller.StationBuilder.getTrackTypeID
Javadoc:
No Javadoc available
Method code:
public int getTrackTypeID(String string) {
ReadOnlyWorld w = executor.getWorld();
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule r = (TrackRule) w.get(SKEY.TRACK_RULES, i);
if (string.equals(r.getTypeName())) {
return i;
}
}
throw new NoSuchElementException();
}
Outgoing Methods (calls):
jfreerails.controller.StationBuilder.setStationType
Javadoc:
No Javadoc available
Method code:
public void setStationType(int ruleNumber) {
this.ruleNumber = ruleNumber;
}
No outgoing methods.
jfreerails.controller.StationBuilder.tryBuildingStation
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryBuildingStation(ImPoint p) {
ReadOnlyWorld world = executor.getWorld();
FreerailsPrincipal principal = executor.getPrincipal();
AddStationPreMove preMove = AddStationPreMove.newStation(p,
this.ruleNumber, principal);
Move m = preMove.generateMove(world);
MoveStatus ms = executor.tryDoMove(m);
return ms;
}
Outgoing Methods (calls):
jfreerails.controller.StationBuilderTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
super.setUp();
w = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(w, 0);
ModelRoot mr = new ModelRootImpl();
trackBuilder = new TrackMoveProducer(me, w, mr);
stationBuilder = new StationBuilder(me);
}
Outgoing Methods (calls):
jfreerails.controller.StationBuilderTest.testBuildStation
Javadoc:
No Javadoc available
Method code:
public void testBuildStation() {
stationBuilder
.setStationType(stationBuilder.getTrackTypeID("terminal"));
Step[] track = { EAST, EAST, EAST };
MoveStatus ms = trackBuilder.buildTrack(new ImPoint(10, 10), track);
assertTrue(ms.ok);
assertTrue(stationBuilder.tryBuildingStation(new ImPoint(10, 10)).ok);
assertTrue(stationBuilder.tryBuildingStation(new ImPoint(13, 10)).ok);
MoveStatus ms1 = stationBuilder.buildStation(new ImPoint(10, 10));
assertTrue(ms1.ok);
MoveStatus ms2 = stationBuilder.buildStation(new ImPoint(13, 10));
assertFalse(ms2.ok);
}
Outgoing Methods (calls):
jfreerails.controller.StationBuilderTest.testCanBuiltStationHere
Javadoc:
No Javadoc available
Method code:
public void testCanBuiltStationHere() {
}
No outgoing methods.
jfreerails.controller.Stats.calProfit
Javadoc:
No Javadoc available
Method code:
private void calProfit(){
long profitValue = operatingFunds.getAmount() + track.getAmount()
+ stations.getAmount() + rollingStock.getAmount()
+ industries.getAmount() + loans.getAmount()
+ equity.getAmount() + treasuryStock.getAmount()
+ otherRrStock.getAmount();
profit= new Money(profitValue);
}
Outgoing Methods (calls):
jfreerails.controller.StockPriceCalculator.calStockPrice
Javadoc:
No Javadoc available
Method code:
static Money calStockPrice(long netWorth, long profitLastyear, int publicShares, int otherRRShares){
if((publicShares + otherRRShares) == 0 ) return new Money(Long.MAX_VALUE);
long price = 2 * (5 * profitLastyear + netWorth) /(2 * publicShares + otherRRShares);
return new Money(price);
}
No outgoing methods.
jfreerails.controller.StockPriceCalculator.calculate
Javadoc:
No Javadoc available
Method code:
public StockPrice[] calculate() {
StockPrice[] stockPrices = new StockPrice[w.getNumberOfPlayers()];
for (int playerId = 0; playerId < stockPrices.length; playerId++) {
long profitLastYear;
if(isFirstYear(playerId)){
profitLastYear = 100000;
}else{
profitLastYear = profitsLastYear(playerId);
}
long netWorth = netWorth(playerId);
int publicShares = sharesOwnedByPublic(playerId);
int otherRRShares = sharesOwnedByOtherPlayers(playerId);
stockPrices[playerId] = new StockPrice(netWorth, profitLastYear, publicShares, otherRRShares);
}
return stockPrices;
}
Outgoing Methods (calls):
jfreerails.controller.StockPriceCalculator.isFirstYear
Javadoc:
/** Returns true if the current time in the same year as the first transaction for the * specified player. */
Method code:
/** Returns true if the current time in the same year as the first transaction for the
* specified player.
*/
boolean isFirstYear(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
GameTime firstTransactionTime = w.getTransactionTimeStamp(pr, 0);
GameCalendar calendar = (GameCalendar)w.get(ITEM.CALENDAR);
int year = calendar.getYear(firstTransactionTime.getTicks());
GameTime currentTime = w.currentTime();
int currentYear = calendar.getYear(currentTime.getTicks());
return year == currentYear;
}
Outgoing Methods (calls):
jfreerails.controller.StockPriceCalculator.netWorth
Javadoc:
/** Returns the players networth at the start of this year.*/
Method code:
/** Returns the players networth at the start of this year.*/
long netWorth(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
NetWorthCalculator nwc = new NetWorthCalculator(w, pr);
//Set the interval to beginning of time to start of this year.
GameCalendar calendar = (GameCalendar)w.get(ITEM.CALENDAR);
GameTime currentTime = w.currentTime();
int currentYear = calendar.getYear(currentTime.getTicks());
int ticksAtStartOfyear = calendar.getTicks(currentYear);
GameTime[] times = {GameTime.BIG_BANG, new GameTime(ticksAtStartOfyear + 1)};
nwc.setTimes(times);
return nwc.calculateValue().getAmount();
}
Outgoing Methods (calls):
jfreerails.controller.StockPriceCalculator.profitsLastYear
Javadoc:
No Javadoc available
Method code:
long profitsLastYear(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
GameCalendar calendar = (GameCalendar)w.get(ITEM.CALENDAR);
GameTime currentTime = w.currentTime();
int currentYear = calendar.getYear(currentTime.getTicks());
int lastyear = currentYear - 1;
int ticksAtStartOfyear = calendar.getTicks(currentYear);
int ticksAtStartOfLastYear = calendar.getTicks(lastyear);
GameTime[] interval = {new GameTime(ticksAtStartOfLastYear), new GameTime(ticksAtStartOfyear)};
TransactionAggregator aggregator = new TransactionAggregator(w, pr){
@Override
protected boolean condition(int transactionID) {
Transaction t = super.w.getTransaction(super.principal,
transactionID);
if (t instanceof AddItemTransaction) {
// Since buying something is just converting one asset type to
// another.
return false;
}
return true;
}
};
aggregator.setTimes(interval);
return aggregator.calculateValue().getAmount();
}
Outgoing Methods (calls):
jfreerails.controller.StockPriceCalculator.sharesOwnedByOtherPlayers
Javadoc:
No Javadoc available
Method code:
int sharesOwnedByOtherPlayers(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
FinancialDataGatherer gatherer = new FinancialDataGatherer(w, pr);
int[] stakes = gatherer.getStockInThisRRs();
int total = 0;
for (int i = 0; i < stakes.length; i++) {
if(i != playerId){
total+= stakes[i];
}
}
return total;
}
Outgoing Methods (calls):
jfreerails.controller.StockPriceCalculator.sharesOwnedByPublic
Javadoc:
No Javadoc available
Method code:
int sharesOwnedByPublic(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
FinancialDataGatherer gatherer = new FinancialDataGatherer(w, pr);
return gatherer.sharesHeldByPublic();
}
Outgoing Methods (calls):
jfreerails.controller.StockPriceCalculatorTest.addIncome
Javadoc:
No Javadoc available
Method code:
private void addIncome(long income) {
CargoBatch batch = new CargoBatch(0, 0, 0, 0, 0);
Transaction t = new DeliverCargoReceipt(new Money(income), 10, 0,
batch, 0);
FreerailsPrincipal princ = w.getPlayer(0).getPrincipal();
w.addTransaction(princ, t);
}
Outgoing Methods (calls):
jfreerails.controller.StockPriceCalculatorTest.advanceTimeOneTick
Javadoc:
No Javadoc available
Method code:
private void advanceTimeOneTick() {
int currentTicks = w.currentTime().getTicks();
GameTime newTime = new GameTime(currentTicks + 1);
w.setTime(newTime);
}
Outgoing Methods (calls):
jfreerails.controller.StockPriceCalculatorTest.advanceTimeOneYear
Javadoc:
No Javadoc available
Method code:
private void advanceTimeOneYear() {
GameCalendar calendar = (GameCalendar) w.get(ITEM.CALENDAR);
int tpy = calendar.getTicksPerYear();
int currentTicks = w.currentTime().getTicks();
GameTime newTime = new GameTime(currentTicks + tpy);
w.setTime(newTime);
}
Outgoing Methods (calls):
jfreerails.controller.StockPriceCalculatorTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
super.setUp();
w = MapFixtureFactory2.getCopy();
calc = new StockPriceCalculator(w);
}
Outgoing Methods (calls):
jfreerails.controller.StockPriceCalculatorTest.testCalculate
Javadoc:
No Javadoc available
Method code:
public void testCalculate() {
Money stockPrice = calc.calculate()[0].currentPrice;
assertEquals(new Money(10), stockPrice);
advanceTimeOneTick();
addIncome(100000);
calc.calculate();
stockPrice = calc.calculate()[0].currentPrice;
assertEquals(new Money(10), stockPrice);
advanceTimeOneYear();
calc.calculate();
stockPrice = calc.calculate()[0].currentPrice;
assertEquals(new Money(11), stockPrice);
}
Outgoing Methods (calls):
jfreerails.controller.StockPriceCalculatorTest.testIsFirstYear
Javadoc:
No Javadoc available
Method code:
/*
* Test method for
* 'jfreerails.controller.StockPriceCalculator.isFirstYear(int)'
*/
public void testIsFirstYear() {
assertTrue(calc.isFirstYear(0));
GameCalendar calendar = (GameCalendar) w.get(ITEM.CALENDAR);
int tpy = calendar.getTicksPerYear();
int currentTicks = w.currentTime().getTicks();
GameTime newTime = new GameTime(currentTicks + tpy + 1);
w.setTime(newTime);
assertFalse(calc.isFirstYear(0));
newTime = new GameTime(currentTicks + tpy - 1);
w.setTime(newTime);
assertTrue(calc.isFirstYear(0));
}
Outgoing Methods (calls):
jfreerails.controller.StockPriceCalculatorTest.testNetWorth
Javadoc:
No Javadoc available
Method code:
/*
* Test method for
* 'jfreerails.controller.StockPriceCalculator.netWorth(int)'
*/
public void testNetWorth() {
long initialNetworth = 500000;
assertEquals(initialNetworth, calc.netWorth(0));
int currentTicks = w.currentTime().getTicks();
GameTime newTime = new GameTime(currentTicks + 1);
w.setTime(newTime);
CargoBatch batch = new CargoBatch(0, 0, 0, 0, 0);
long income = 100000;
Transaction t = new DeliverCargoReceipt(new Money(income), 10, 0,
batch, 0);
FreerailsPrincipal princ = w.getPlayer(0).getPrincipal();
w.addTransaction(princ, t);
assertEquals(initialNetworth, calc.netWorth(0));
GameCalendar calendar = (GameCalendar) w.get(ITEM.CALENDAR);
int tpy = calendar.getTicksPerYear();
currentTicks = w.currentTime().getTicks();
newTime = new GameTime(currentTicks + tpy);
w.setTime(newTime);
long expectedNetWorth = initialNetworth + income;
assertEquals(expectedNetWorth, calc.netWorth(0));
}
Outgoing Methods (calls):
jfreerails.controller.StockPriceCalculatorTest.testProfitsLastYear
Javadoc:
No Javadoc available
Method code:
/*
* Test method for
* 'jfreerails.controller.StockPriceCalculator.profitsLastYear(int)'
*/
public void testProfitsLastYear() {
assertEquals(0, calc.profitsLastYear(0));
int currentTicks = w.currentTime().getTicks();
GameTime newTime = new GameTime(currentTicks + 10);
w.setTime(newTime);
assertEquals(0, calc.profitsLastYear(0));
long income = 100000;
addIncome(income);
assertEquals(0, calc.profitsLastYear(0));
advanceTimeOneYear();
assertEquals(income, calc.profitsLastYear(0));
}
Outgoing Methods (calls):
jfreerails.controller.TimeTickPreMove.generateMove
Javadoc:
No Javadoc available
Method code:
public Move generateMove(ReadOnlyWorld w) {
return TimeTickMove.getMove(w);
}
Outgoing Methods (calls):
jfreerails.controller.TimeTickPreMove.readResolve
Javadoc:
No Javadoc available
Method code:
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
No outgoing methods.
jfreerails.controller.ToAndFroPathIterator.hasNext
Javadoc:
No Javadoc available
Method code:
public boolean hasNext() {
if (list.size() < 2) {
return false;
}
return true;
}
No outgoing methods.
jfreerails.controller.ToAndFroPathIterator.nextIterator
Javadoc:
No Javadoc available
Method code:
private void nextIterator() {
path = new FreerailsPathIteratorImpl(list, forwards);
}
No outgoing methods.
jfreerails.controller.ToAndFroPathIterator.nextSegment
Javadoc:
No Javadoc available
Method code:
public void nextSegment(IntLine line) {
if (this.hasNext()) {
if (!path.hasNext()) {
forwards = !forwards;
path = new FreerailsPathIteratorImpl(list, forwards);
}
path.nextSegment(line);
} else {
throw new NoSuchElementException();
}
}
Outgoing Methods (calls):
jfreerails.controller.ToAndFroPathIteratorTest.assertLineEquals
Javadoc:
No Javadoc available
Method code:
private void assertLineEquals(int x1, int y1, int x2, int y2, IntLine line) {
assertEquals(x1, line.x1);
assertEquals(x2, line.x2);
assertEquals(y1, line.y1);
assertEquals(y2, line.y2);
}
No outgoing methods.
jfreerails.controller.ToAndFroPathIteratorTest.testNextSegment
Javadoc:
No Javadoc available
Method code:
public void testNextSegment() {
List<Point> l = new ArrayList<Point>();
IntLine line = new IntLine();
l.add(new Point(0, 1));
l.add(new Point(10, 11));
l.add(new Point(20, 22));
FreerailsPathIterator it = new ToAndFroPathIterator(l);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(0, 1, 10, 11, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(10, 11, 20, 22, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(20, 22, 10, 11, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(10, 11, 0, 1, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(0, 1, 10, 11, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(10, 11, 20, 22, line);
}
Outgoing Methods (calls):
jfreerails.controller.TrackBuildingTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
super.setUp();
w = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(w, 0);
ModelRoot mr = new ModelRootImpl();
producer = new TrackMoveProducer(me, w, mr);
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
pathFinder = new TrackPathFinder(w, principal);
stationBuilder = new StationBuilder(me);
bts = BuildTrackStrategy.getDefault(w);
}
Outgoing Methods (calls):
jfreerails.controller.TrackBuildingTest.testBuildingOneTrackPiece
Javadoc:
/** Tests building track from 5,5 to 6,5 */
Method code:
/** Tests building track from 5,5 to 6,5 */
public void testBuildingOneTrackPiece() {
ImPoint from = new ImPoint(5, 5);
ImPoint to = new ImPoint(6, 5);
try {
// Check there is no track before we build it.
TrackPiece tp1 = ((FreerailsTile) w.getTile(5, 5)).getTrackPiece();
assertEquals(NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER, tp1
.getTrackTypeID());
TrackPiece tp2 = ((FreerailsTile) w.getTile(6, 5)).getTrackPiece();
assertEquals(NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER, tp2
.getTrackTypeID());
pathFinder.setupSearch(from, to, bts);
pathFinder.search(-1);
assertEquals(pathFinder.getStatus(),
IncrementalPathFinder.PATH_FOUND);
Step[] path = pathFinder.pathAsVectors();
assertEquals(path.length, 1);
assertEquals(Step.EAST, path[0]);
MoveStatus ms = producer.buildTrack(from, path);
assertTrue(ms.message, ms.ok);
// Check track has been built.
tp1 = ((FreerailsTile) w.getTile(5, 5)).getTrackPiece();
assertEquals(0, tp1.getTrackTypeID());
tp2 = ((FreerailsTile) w.getTile(6, 5)).getTrackPiece();
assertEquals(0, tp2.getTrackTypeID());
} catch (PathNotFoundException e) {
fail();
}
}
Outgoing Methods (calls):
jfreerails.controller.TrackBuildingTest.testBuildingStraight
Javadoc:
/** Tests building track from 5,5 to 10,5 */
Method code:
/** Tests building track from 5,5 to 10,5 */
public void testBuildingStraight() {
ImPoint from = new ImPoint(5, 5);
ImPoint to = new ImPoint(10, 5);
try {
// Check there is no track before we build it.
for (int x = 5; x <= 10; x++) {
TrackPiece tp = ((FreerailsTile) w.getTile(x, 5)).getTrackPiece();
assertEquals(NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER, tp
.getTrackTypeID());
}
pathFinder.setupSearch(from, to, bts);
pathFinder.search(-1);
assertEquals(pathFinder.getStatus(),
IncrementalPathFinder.PATH_FOUND);
Step[] path = pathFinder.pathAsVectors();
assertEquals(path.length, 5);
for (int i = 0; i < 5; i++) {
assertEquals(Step.EAST, path[i]);
}
MoveStatus ms = producer.buildTrack(from, path);
assertTrue(ms.message, ms.ok);
// Check track has been built.
for (int x = 5; x <= 10; x++) {
TrackPiece tp = ((FreerailsTile) w.getTile(x, 5)).getTrackPiece();
assertEquals(0, tp.getTrackTypeID());
}
} catch (PathNotFoundException e) {
fail();
}
}
Outgoing Methods (calls):
jfreerails.controller.TrackBuildingTest.testDoubleTrackProblem
Javadoc:
/** * There is a bug where if you build a straight section of double track * going E, then move the cursor to the end and attempt to build more double * track going SE, the track path finder builds a loop rather than just * building track going SE * */
Method code:
/**
* There is a bug where if you build a straight section of double track
* going E, then move the cursor to the end and attempt to build more double
* track going SE, the track path finder builds a loop rather than just
* building track going SE
*
*/
public void testDoubleTrackProblem() {
try {
int trackTypeID = stationBuilder.getTrackTypeID("double track");
bts = BuildTrackStrategy.getSingleRuleInstance(trackTypeID, w);
producer.setBuildTrackStrategy(bts);
ImPoint a = new ImPoint(5, 5);
ImPoint b = new ImPoint(6, 5);
ImPoint c = new ImPoint(7, 6);
pathFinder.setupSearch(a, b, bts);
pathFinder.search(-1);
Step[] path = pathFinder.pathAsVectors();
Step[] expectedPath = { EAST };
assertTrue(Arrays.equals(expectedPath, path));
MoveStatus ms = producer.buildTrack(a, path);
assertTrue(ms.ok);
TrackPiece tp = ((FreerailsTile) w.getTile(b.x, b.y)).getTrackPiece();
assertEquals("We just build double track here.", trackTypeID, tp
.getTrackTypeID());
pathFinder.setupSearch(b, c, bts);
pathFinder.search(-1);
path = pathFinder.pathAsVectors();
assertEquals(1, path.length);
expectedPath = new Step[] { SOUTH_EAST };
assertTrue(Arrays.equals(expectedPath, path));
} catch (PathNotFoundException e) {
fail();
}
}
Outgoing Methods (calls):
jfreerails.controller.TrackBuildingTest.testStartSearchOnSharpCurve
Javadoc:
/** * There is a bug where if you try to start building track on a 90 degree * bend, no track path is found even when one should exist. * */
Method code:
/**
* There is a bug where if you try to start building track on a 90 degree
* bend, no track path is found even when one should exist.
*
*/
public void testStartSearchOnSharpCurve() {
try {
ImPoint from = new ImPoint(5, 5);
Step[] path = { EAST, SOUTH };
MoveStatus ms = producer.buildTrack(from, path);
assertTrue(ms.ok);
pathFinder.setupSearch(new ImPoint(6, 5), new ImPoint(6, 7), bts);
pathFinder.search(-1);
path = pathFinder.pathAsVectors();
assertEquals(2, path.length);
assertEquals(SOUTH, path[0]);
assertEquals(SOUTH, path[1]);
} catch (PathNotFoundException e) {
fail();
}
}
Outgoing Methods (calls):
jfreerails.controller.TrackBuildingTest.testTerminalProblem
Javadoc:
/** * There is a bug where if a section of track has a terminal on the end, you * cannot extend the track through the terminal. Instead, the track path * finder finds a route that misses out the terminal. * */
Method code:
/**
* There is a bug where if a section of track has a terminal on the end, you
* cannot extend the track through the terminal. Instead, the track path
* finder finds a route that misses out the terminal.
*
*/
public void testTerminalProblem() {
try {
ImPoint from = new ImPoint(5, 5);
Step[] path = { EAST, EAST, EAST };
MoveStatus ms = producer.buildTrack(from, path);
assertTrue(ms.ok);
int terminalStationType = stationBuilder.getTrackTypeID("terminal");
stationBuilder.setStationType(terminalStationType);
ms = stationBuilder.buildStation(new ImPoint(8, 5));
assertTrue(ms.ok);
pathFinder.setupSearch(new ImPoint(7, 5), new ImPoint(9, 5), bts);
pathFinder.search(-1);
path = pathFinder.pathAsVectors();
assertEquals(2, path.length);
Step[] expectedPath = { EAST, EAST };
assertTrue(Arrays.equals(expectedPath, path));
} catch (PathNotFoundException e) {
fail();
}
}
Outgoing Methods (calls):
jfreerails.controller.TrackMoveProducer.buildTrack
Javadoc:
No Javadoc available
Method code:
public MoveStatus buildTrack(ImPoint from, Step[] path) {
MoveStatus returnValue = MoveStatus.MOVE_OK;
int x = from.x;
int y = from.y;
for (int i = 0; i < path.length; i++) {
returnValue = buildTrack(new ImPoint(x, y), path[i]);
x += path[i].deltaX;
y += path[i].deltaY;
if (!returnValue.ok) {
return returnValue;
}
}
return returnValue;
}
Outgoing Methods (calls):
jfreerails.controller.TrackMoveProducer.clearStackIfStale
Javadoc:
/** * Moves are only un-doable if no game time has passed since they they were * executed. This method clears the move stack if the moves were added to * the stack at a time other than the current time. */
Method code:
/**
* Moves are only un-doable if no game time has passed since they they were
* executed. This method clears the move stack if the moves were added to
* the stack at a time other than the current time.
*/
private void clearStackIfStale() {
ReadOnlyWorld w = executor.getWorld();
GameTime currentTime = w.currentTime();
if (!currentTime.equals(lastMoveTime)) {
moveStack.clear();
lastMoveTime = currentTime;
}
}
Outgoing Methods (calls):
jfreerails.controller.TrackMoveProducer.getBuildMode
Javadoc:
No Javadoc available
Method code:
public BuildMode getBuildMode() {
return (BuildMode) mr.getProperty(Property.TRACK_BUILDER_MODE);
}
Outgoing Methods (calls):
jfreerails.controller.TrackMoveProducer.getBuildTrackStrategy
Javadoc:
No Javadoc available
Method code:
public BuildTrackStrategy getBuildTrackStrategy() {
return (BuildTrackStrategy) mr.getProperty(Property.BUILD_TRACK_STRATEGY);
}
Outgoing Methods (calls):
jfreerails.controller.TrackMoveProducer.getTrackBuilderMode
Javadoc:
No Javadoc available
Method code:
public BuildMode getTrackBuilderMode() {
return getBuildMode();
}
Outgoing Methods (calls):
jfreerails.controller.TrackMoveProducer.isStationHere
Javadoc:
No Javadoc available
Method code:
private boolean isStationHere(ImPoint p) {
ReadOnlyWorld w = executor.getWorld();
FreerailsTile tile = (FreerailsTile) w.getTile(p.x, p.y);
return tile.getTrackPiece().getTrackRule().isStation();
}
Outgoing Methods (calls):
jfreerails.controller.TrackMoveProducer.sendMove
Javadoc:
No Javadoc available
Method code:
private MoveStatus sendMove(Move m) {
MoveStatus ms = executor.doMove(m);
if (ms.isOk()) {
clearStackIfStale();
moveStack.add(m);
}
return ms;
}
Outgoing Methods (calls):
jfreerails.controller.TrackMoveProducer.setBuildMode
Javadoc:
No Javadoc available
Method code:
public void setBuildMode(BuildMode buildMode) {
mr.setProperty(Property.TRACK_BUILDER_MODE, buildMode);
}
Outgoing Methods (calls):
jfreerails.controller.TrackMoveProducer.setBuildTrackStrategy
Javadoc:
No Javadoc available
Method code:
public void setBuildTrackStrategy(BuildTrackStrategy buildTrackStrategy) {
mr.setProperty(Property.BUILD_TRACK_STRATEGY, buildTrackStrategy);
}
Outgoing Methods (calls):
jfreerails.controller.TrackMoveProducer.setTrackBuilderMode
Javadoc:
No Javadoc available
Method code:
public void setTrackBuilderMode(BuildMode i) {
setBuildMode(i);
}
Outgoing Methods (calls):
jfreerails.controller.TrackMoveProducer.undoLastTrackMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus undoLastTrackMove() {
clearStackIfStale();
if (moveStack.size() > 0) {
Move m = moveStack.pop();
UndoMove undoMove = new UndoMove(m);
MoveStatus ms = executor.doMove(undoMove);
if (!ms.ok) {
return MoveStatus.moveFailed("Can not undo building track!");
}
return ms;
}
return MoveStatus.moveFailed("No track to undo building!");
}
Outgoing Methods (calls):
jfreerails.controller.TrackMoveProducer.upgradeTrack
Javadoc:
No Javadoc available
Method code:
private MoveStatus upgradeTrack(ImPoint point, int trackRuleID) {
ReadOnlyWorld w = executor.getWorld();
TrackPiece before = ((FreerailsTile) w.getTile(point.x, point.y)).getTrackPiece();
/* Check whether there is track here. */
if (before.getTrackTypeID() == NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
return MoveStatus.moveFailed("No track to upgrade.");
}
FreerailsPrincipal principal = executor.getPrincipal();
int owner = ChangeTrackPieceCompositeMove.getOwner(principal, w);
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, trackRuleID);
TrackPiece after = new TrackPieceImpl(before.getTrackConfiguration(),
trackRule, owner, trackRuleID);
/* We don't want to 'upgrade' a station to track. See bug 874416. */
if (before.getTrackRule().isStation()) {
return MoveStatus
.moveFailed("No need to upgrade track at station.");
}
Move move = UpgradeTrackMove.generateMove(before, after, point);
Move move2 = transactionsGenerator.addTransactions(move);
return sendMove(move2);
}
Outgoing Methods (calls):
jfreerails.controller.TrackPathFinder.abandonSearch
Javadoc:
No Javadoc available
Method code:
public void abandonSearch() {
pathFinder.abandonSearch();
}
Outgoing Methods (calls):
jfreerails.controller.TrackPathFinder.convertPath2Points
Javadoc:
No Javadoc available
Method code:
private List<ImPoint> convertPath2Points(IntArray path) {
PositionOnTrack progress = new PositionOnTrack();
List<ImPoint> proposedTrack = new ArrayList<ImPoint>();
ImPoint p;
for (int i = 0; i < path.size(); i++) {
progress.setValuesFromInt(path.get(i));
p = new ImPoint(progress.getX(), progress.getY());
proposedTrack.add(p);
logger.fine("Adding point " + p);
}
return proposedTrack;
}
Outgoing Methods (calls):
jfreerails.controller.TrackPathFinder.findTargets
Javadoc:
No Javadoc available
Method code:
private int[] findTargets(ImPoint targetPoint) {
FreerailsTile tile = (FreerailsTile) world.getTile(targetPoint.x,
targetPoint.y);
TrackPiece trackPiece = tile.getTrackPiece();
int ruleNumber = trackPiece.getTrackTypeID();
int[] targetInts;
if (tile.hasTrack()) {
/*
* If there is already track here, we need to check what directions
* we can build in without creating an illegal track config.
*/
TrackRule trackRule = (TrackRule) world.get(SKEY.TRACK_RULES,
ruleNumber);
/* Count number of possible directions. */
ArrayList<Step> possibleDirections = new ArrayList<Step>();
for (int i = 0; i < 8; i++) {
Step direction = Step.getInstance(i);
TrackConfiguration config = trackPiece.getTrackConfiguration();
TrackConfiguration testConfig = TrackConfiguration.add(config,
direction);
if (trackRule.trackPieceIsLegal(testConfig)) {
possibleDirections.add(direction);
}
}
/* Put them into an array. */
targetInts = new int[possibleDirections.size()];
for (int i = 0; i < targetInts.length; i++) {
Step direction = possibleDirections.get(i);
PositionOnTrack targetPot = PositionOnTrack.createFacing(
targetPoint.x, targetPoint.y, direction);
targetInts[i] = targetPot.toInt();
}
} else {
/* If there is no track here, we can go in any direction. */
targetInts = new int[8];
for (int i = 0; i < 8; i++) {
PositionOnTrack targetPot = PositionOnTrack.createComingFrom(
targetPoint.x, targetPoint.y, Step.getInstance(i));
targetInts[i] = targetPot.toInt();
}
}
return targetInts;
}
Outgoing Methods (calls):
jfreerails.controller.TrackPathFinder.generatePath
Javadoc:
No Javadoc available
Method code:
public List generatePath(ImPoint start, ImPoint targetPoint,
BuildTrackStrategy bts) throws PathNotFoundException {
setupSearch(start, targetPoint, bts);
pathFinder.search(-1);
IntArray path = pathFinder.retrievePath();
List proposedTrack = convertPath2Points(path);
return proposedTrack;
}
Outgoing Methods (calls):
jfreerails.controller.TrackPathFinder.getStatus
Javadoc:
/** * Returns the current status of the path finding algorithm. * This method delegates the request to the underlying * {@link jfreerails.controller.SimpleAStarPathFinder} instance * to retrieve the status of the path finding operation. * * @return an integer representing the current status of the path finder. */
Method code:
public int getStatus() {
return pathFinder.getStatus();
}
Outgoing Methods (calls):
jfreerails.controller.TrackPathFinder.pathAsPoints
Javadoc:
No Javadoc available
Method code:
public List<ImPoint> pathAsPoints() {
IntArray path = pathFinder.retrievePath();
return convertPath2Points(path);
}
Outgoing Methods (calls):
jfreerails.controller.TrackPathFinder.pathAsVectors
Javadoc:
No Javadoc available
Method code:
public Step[] pathAsVectors() {
IntArray path = pathFinder.retrievePath();
int size = path.size();
Step[] vectors = new Step[size];
PositionOnTrack progress = new PositionOnTrack();
int x = startPoint.x;
int y = startPoint.y;
for (int i = 0; i < size; i++) {
progress.setValuesFromInt(path.get(i));
int x2 = progress.getX();
int y2 = progress.getY();
vectors[i] = Step.getInstance(x2 - x, y2 - y);
x = x2;
y = y2;
}
return vectors;
}
Outgoing Methods (calls):
jfreerails.controller.TrackPathFinder.setupSearch
Javadoc:
No Javadoc available
Method code:
public void setupSearch(ImPoint startPoint, ImPoint targetPoint,
BuildTrackStrategy bts) throws PathNotFoundException {
logger
.fine("Find track path from " + startPoint + " to "
+ targetPoint);
this.startPoint = startPoint;
int[] targetInts = findTargets(targetPoint);
int[] startInts = findTargets(startPoint);
BuildTrackExplorer explorer = new BuildTrackExplorer(world,
principal, startPoint, targetPoint);
explorer.setBuildTrackStrategy(bts);
pathFinder.setupSearch(startInts, targetInts, explorer);
}
Outgoing Methods (calls):
jfreerails.controller.TrackPathFinderTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
world = new WorldImpl(20, 20);
world.addPlayer(testPlayer);
world.set(ITEM.GAME_RULES, GameRules.NO_RESTRICTIONS);
MapFixtureFactory.generateTrackRuleList(world);
}
Outgoing Methods (calls):
jfreerails.controller.TrackPathFinderTest.testGeneratePath
Javadoc:
No Javadoc available
Method code:
public void testGeneratePath() {
try {
BuildTrackStrategy bts = BuildTrackStrategy.getSingleRuleInstance(
0, world);
TrackPathFinder pathFinder = new TrackPathFinder(world, testPlayer
.getPrincipal());
List l = pathFinder.generatePath(new ImPoint(0, 0), new ImPoint(0,
5), bts);
assertEquals(5, l.size());
List list2 = pathFinder.generatePath(new ImPoint(5, 5),
new ImPoint(5, 10), bts);
assertEquals(5, list2.size());
list2 = pathFinder.generatePath(new ImPoint(5, 10), new ImPoint(5,
5), bts);
assertEquals(5, list2.size());
} catch (PathNotFoundException e) {
fail();
}
}
Outgoing Methods (calls):
jfreerails.controller.TrainAccessor.findCurrentMotion
Javadoc:
No Javadoc available
Method code:
public TrainMotion findCurrentMotion(double time) {
ActivityIterator ai = w.getActivities(p, id);
ai.gotoLastActivity();
while (ai.getStartTime() > time && ai.hasPrevious()) {
ai.previousActivity();
}
return (TrainMotion) ai.getActivity();
}
Outgoing Methods (calls):
jfreerails.controller.TrainAccessor.findPosition
Javadoc:
No Javadoc available
Method code:
public TrainPositionOnMap findPosition(double time) {
ActivityIterator ai = w.getActivities(p, id);
ai.gotoLastActivity();
while (ai.getStartTime() > time && ai.hasPrevious()) {
ai.previousActivity();
}
double dt = time - ai.getStartTime();
dt = Math.min(dt, ai.getDuration());
TrainMotion tm = (TrainMotion) ai.getActivity();
return tm.getState(dt);
}
Outgoing Methods (calls):
jfreerails.controller.TrainAccessor.getCargoBundle
Javadoc:
No Javadoc available
Method code:
public ImmutableCargoBundle getCargoBundle() {
TrainModel train = getTrain();
return (ImmutableCargoBundle) w.get(p, KEY.CARGO_BUNDLES, train
.getCargoBundleID());
}
Outgoing Methods (calls):
jfreerails.controller.TrainAccessor.getId
Javadoc:
/** * Returns the unique identifier of this train accessor. * * @return the unique identifier of the train accessor */
Method code:
public int getId() {
return id;
}
No outgoing methods.
jfreerails.controller.TrainAccessor.getSchedule
Javadoc:
No Javadoc available
Method code:
public ImmutableSchedule getSchedule() {
TrainModel train = getTrain();
return (ImmutableSchedule) w.get(p, KEY.TRAIN_SCHEDULES, train
.getScheduleID());
}
Outgoing Methods (calls):
jfreerails.controller.TrainAccessor.getStationId
Javadoc:
/** * @return the id of the station the train is currently at, or -1 if no * current station. * */
Method code:
/**
* @return the id of the station the train is currently at, or -1 if no
* current station.
*
*/
public int getStationId(double time){
TrainMotion tm = findCurrentMotion(time);
PositionOnTrack pot = tm.getFinalPosition();
int x = pot.getX();
int y = pot.getY();
//loop thru the station list to check if train is at the same Point
// as
// a station
for (int i = 0; i < w.size(p, KEY.STATIONS); i++) {
StationModel tempPoint = (StationModel) w.get(p, KEY.STATIONS, i);
if (null != tempPoint && (x == tempPoint.x) && (y == tempPoint.y)) {
return i; // train is at the station at location tempPoint
}
}
return -1;
}
Outgoing Methods (calls):
jfreerails.controller.TrainAccessor.getStatus
Javadoc:
No Javadoc available
Method code:
public SpeedTimeAndStatus.TrainActivity getStatus(double time){
TrainMotion tm = findCurrentMotion(time);
return tm.getActivity();
}
Outgoing Methods (calls):
jfreerails.controller.TrainAccessor.getTarget
Javadoc:
/** * @return the location of the station the train is currently heading * towards. */
Method code:
/**
* @return the location of the station the train is currently heading
* towards.
*/
public ImPoint getTarget() {
TrainModel train = (TrainModel) w.get(p, KEY.TRAINS, id);
int scheduleID = train.getScheduleID();
ImmutableSchedule schedule = (ImmutableSchedule) w.get(
p, KEY.TRAIN_SCHEDULES, scheduleID);
int stationNumber = schedule.getStationToGoto();
if (-1 == stationNumber) {
// There are no stations on the schedule.
return new ImPoint(0, 0);
}
StationModel station = (StationModel) w.get(p,
KEY.STATIONS, stationNumber);
return new ImPoint(station.x, station.y);
}
Outgoing Methods (calls):
jfreerails.controller.TrainAccessor.getTrain
Javadoc:
No Javadoc available
Method code:
public TrainModel getTrain() {
return (TrainModel) w.get(p, KEY.TRAINS, id);
}
Outgoing Methods (calls):
jfreerails.controller.TrainAccessor.isMoving
Javadoc:
No Javadoc available
Method code:
public boolean isMoving(double time){
TrainMotion tm = findCurrentMotion(time);
double speed = tm.getSpeedAtEnd();
return speed != 0;
}
Outgoing Methods (calls):
jfreerails.controller.TrainAccessor.keepWaiting
Javadoc:
/** * Returns true iff all the following hold. * <ol> * <li>The train is waiting for a full load at some station X.</li> * <li>The current train order tells the train to goto station X.</li> * <li>The current train order tells the train to wait for a full load.</li> * <li>The current train order specifies a consist that matches the train's current consist.</li> * </ol> * */
Method code:
/**
* Returns true iff all the following hold.
* <ol>
* <li>The train is waiting for a full load at some station X.</li>
* <li>The current train order tells the train to goto station X.</li>
* <li>The current train order tells the train to wait for a full load.</li>
* <li>The current train order specifies a consist that matches the train's current consist.</li>
* </ol>
*
*/
public boolean keepWaiting(){
double time = w.currentTime().getTicks();
int stationId = getStationId(time);
if (stationId == -1)
return false;
SpeedTimeAndStatus.TrainActivity act = getStatus(time);
if (act != TrainActivity.WAITING_FOR_FULL_LOAD)
return false;
ImmutableSchedule schedule = getSchedule();
if(schedule.getNumOrders() <1){
//We end up here if all the train orders are deleted while a train
//is waiting for a full load.
return false;
}
TrainOrdersModel order = schedule.getOrder(schedule.getOrderToGoto());
if (order.stationId != stationId)
return false;
if (!order.waitUntilFull)
return false;
TrainModel train = getTrain();
return order.getConsist().equals(train.getConsist());
}
Outgoing Methods (calls):
jfreerails.controller.TrainAccessor.occupiedTrackSection
Javadoc:
No Javadoc available
Method code:
public HashSet<TrackSection> occupiedTrackSection(double time){
TrainMotion tm = findCurrentMotion(time);
PathOnTiles path = tm.getPath();
HashSet<TrackSection> sections = new HashSet<TrackSection>();
ImPoint start = path.getStart();
int x = start.x;
int y = start.y;
for (int i = 0; i < path.steps(); i++) {
Step s = path.getStep(i);
ImPoint tile = new ImPoint(x, y);
x+=s.deltaX;
y+=s.deltaY;
sections.add(new TrackSection(s, tile));
}
return sections;
}
Outgoing Methods (calls):
jfreerails.controller.TrainAccessor.spaceAvailable
Javadoc:
/** The space available on the train measured in cargo units.*/
Method code:
/** The space available on the train measured in cargo units.*/
public ImInts spaceAvailable(){
TrainModel train = (TrainModel) w.get(p, KEY.TRAINS, id);
ImmutableCargoBundle bundleOnTrain = (ImmutableCargoBundle) w.get(p,
KEY.CARGO_BUNDLES, train.getCargoBundleID());
return spaceAvailable2(w, bundleOnTrain, train.getConsist());
}
Outgoing Methods (calls):
jfreerails.controller.TrainAccessor.spaceAvailable2
Javadoc:
No Javadoc available
Method code:
public static ImInts spaceAvailable2(ReadOnlyWorld row, ImmutableCargoBundle onTrain, ImInts consist){
// This array will store the amount of space available on the train for
// each cargo type.
final int NUM_CARGO_TYPES = row.size(SKEY.CARGO_TYPES);
int[] spaceAvailable = new int[NUM_CARGO_TYPES];
// First calculate the train's total capacity.
for (int j = 0; j < consist.size(); j++) {
int cargoType = consist.get(j);
spaceAvailable[cargoType] += WagonType.UNITS_OF_CARGO_PER_WAGON;
}
for (int cargoType = 0; cargoType < NUM_CARGO_TYPES; cargoType++) {
spaceAvailable[cargoType]= spaceAvailable[cargoType] - onTrain.getAmount(cargoType);
}
return new ImInts(spaceAvailable);
}
Outgoing Methods (calls):
jfreerails.controller.TrainAccessor.trackExists
Javadoc:
/** * Checks the track under the train's final position still exists (i.e. * has not been bulldozed). */
Method code:
/**
* Checks the track under the train's final position still exists (i.e.
* has not been bulldozed).
*/
public boolean trackExists() {
ActivityIterator ai = w.getActivities(p, id);
ai.gotoLastActivity();
TrainMotion tm = (TrainMotion) ai.getActivity();
PositionOnTrack pot = tm.getFinalPosition();
int x = pot.getX();
int y = pot.getY();
FreerailsTile tile = (FreerailsTile) w.getTile(x, y);
TrackPiece trackPiece = tile.getTrackPiece();
TrackConfiguration present = trackPiece.getTrackConfiguration();
TrackConfiguration needed = TrackConfiguration.getFlatInstance(pot.cameFrom());
return present.contains(needed);
}
Outgoing Methods (calls):
jfreerails.controller.TrainPathIntIterator.hasNextInt
Javadoc:
No Javadoc available
Method code:
public boolean hasNextInt() {
return trackExplorer.hasNextEdge();
}
Outgoing Methods (calls):
jfreerails.controller.TrainPathIntIterator.nextInt
Javadoc:
No Javadoc available
Method code:
public int nextInt() {
trackExplorer.nextEdge();
trackExplorer.moveForward();
return trackExplorer.getPosition();
}
Outgoing Methods (calls):
jfreerails.controller.TrainStopsHandler.arrivesAtPoint
Javadoc:
No Javadoc available
Method code:
public ImPoint arrivesAtPoint(int x, int y) {
TrainAccessor ta = new TrainAccessor(worldDiffs, principal, trainId);
ImPoint targetPoint = ta.getTarget();
if (x == targetPoint.x && y == targetPoint.y) {
updateTarget();
targetPoint = ta.getTarget();
} else {
int stationNumber = getStationID(x, y);
if (NOT_AT_STATION != stationNumber) {
loadAndUnloadCargo(stationNumber, false, false);
}
}
return targetPoint;
}
Outgoing Methods (calls):
jfreerails.controller.TrainStopsHandler.getMoves
Javadoc:
No Javadoc available
Method code:
public Move getMoves() {
Move m = WorldDiffMove.generate(worldDiffs, WorldDiffMove.Cause.TrainArrives);
worldDiffs.reset();
return m;
}
Outgoing Methods (calls):
jfreerails.controller.TrainStopsHandler.getStationID
Javadoc:
/** * @return the number of the station the train is currently at, or -1 if no * current station. */
Method code:
/**
* @return the number of the station the train is currently at, or -1 if no
* current station.
*/
public int getStationID(int x, int y) {
// loop thru the station list to check if train is at the same Point
// as
// a station
for (int i = 0; i < worldDiffs.size(principal, KEY.STATIONS); i++) {
StationModel tempPoint = (StationModel) worldDiffs.get(principal, KEY.STATIONS, i);
if (null != tempPoint && (x == tempPoint.x) && (y == tempPoint.y)) {
return i; // train is at the station at location tempPoint
}
}
return -1;
// there are no stations that exist where the train is currently
}
Outgoing Methods (calls):
jfreerails.controller.TrainStopsHandler.getTrainLength
Javadoc:
No Javadoc available
Method code:
public int getTrainLength() {
TrainAccessor ta = new TrainAccessor(worldDiffs, principal, trainId);
return ta.getTrain().getLength();
}
Outgoing Methods (calls):
jfreerails.controller.TrainStopsHandler.isTrainFull
Javadoc:
No Javadoc available
Method code:
public boolean isTrainFull() {
TrainAccessor train = new TrainAccessor(worldDiffs, principal, trainId);
ImInts spaceAvailable = train.spaceAvailable();
return spaceAvailable.sum() == 0;
}
Outgoing Methods (calls):
jfreerails.controller.TrainStopsHandler.isTrainMoving
Javadoc:
No Javadoc available
Method code:
public boolean isTrainMoving() {
if (refreshWaitingForFullLoad()) {
return false;
}
GameTime time = worldDiffs.currentTime();
return time.getTicks() > this.timeLoadingFinished.getTicks();
}
Outgoing Methods (calls):
jfreerails.controller.TrainStopsHandler.isWaiting4FullLoad
Javadoc:
No Javadoc available
Method code:
public boolean isWaiting4FullLoad() {
TrainModel train = (TrainModel) worldDiffs.get(principal, KEY.TRAINS, this.trainId);
int scheduleID = train.getScheduleID();
ImmutableSchedule schedule = (ImmutableSchedule) worldDiffs.get(principal,
KEY.TRAIN_SCHEDULES, scheduleID);
if(schedule.getNumOrders() == 0){
return false;
}
TrainOrdersModel order = schedule.getOrder(schedule.getOrderToGoto());
return !isTrainFull() && order.waitUntilFull;
}
Outgoing Methods (calls):
jfreerails.controller.TrainStopsHandler.lengthenPath
Javadoc:
/** If wagons are added to a train, we need to increase its length.*/
Method code:
/** If wagons are added to a train, we need to increase its length.*/
static PathOnTiles lengthenPath(ReadOnlyWorld w, PathOnTiles path, int currentTrainLength) {
double pathDistance = path.getTotalDistance();
double extraDistanceNeeded = currentTrainLength - pathDistance;
List<Step> steps = new ArrayList<Step>();
ImPoint start = path.getStart();
Step firstStep = path.getStep(0);
PositionOnTrack nextPot = PositionOnTrack.createComingFrom(start.x, start.y, firstStep);
while( extraDistanceNeeded > 0){
FlatTrackExplorer fte = new FlatTrackExplorer(w, nextPot);
fte.nextEdge();
nextPot.setValuesFromInt(fte.getVertexConnectedByEdge());
Step cameFrom = nextPot.facing();
steps.add(0, cameFrom);
extraDistanceNeeded -= cameFrom.getLength();
}
//Add existing steps
for (int i = 0; i < path.steps(); i++) {
Step step = path.getStep(i);
steps.add(step);
}
ImPoint newStart = new ImPoint(nextPot.getX(), nextPot.getY());
path = new PathOnTiles(newStart, steps);
return path;
}
Outgoing Methods (calls):
jfreerails.controller.TrainStopsHandler.loadAndUnloadCargo
Javadoc:
No Javadoc available
Method code:
void loadAndUnloadCargo(int stationId, boolean waiting, boolean autoConsist) {
// train is at a station so do the cargo processing
DropOffAndPickupCargoMoveGenerator transfer = new DropOffAndPickupCargoMoveGenerator(
trainId, stationId, worldDiffs, principal, waiting, autoConsist);
Move m = transfer.generateMove();
if(null != m){
MoveStatus ms = m.doMove(worldDiffs, principal);
if (!ms.ok)
throw new IllegalStateException(ms.message);
}
}
Outgoing Methods (calls):
jfreerails.controller.TrainStopsHandler.makeTrainWait
Javadoc:
No Javadoc available
Method code:
void makeTrainWait(int ticks) {
GameTime currentTime = worldDiffs.currentTime();
timeLoadingFinished = new GameTime(currentTime.getTicks() + ticks);
}
Outgoing Methods (calls):
jfreerails.controller.TrainStopsHandler.refreshWaitingForFullLoad
Javadoc:
No Javadoc available
Method code:
public boolean refreshWaitingForFullLoad() {
TrainAccessor ta = new TrainAccessor(worldDiffs, principal, trainId);
ImmutableSchedule schedule = ta.getSchedule();
int stationId = ta.getStationId(Double.MAX_VALUE);
if(stationId<0) throw new IllegalStateException();
//The train's orders may have changed...
final int orderToGoto = schedule.getOrderToGoto();
if(-1 == orderToGoto){
//We end up here if all the orders are deleted.
return false;
}
TrainOrdersModel order = schedule.getOrder(orderToGoto);
//Should we go to another station?
if(stationId != order.stationId){
return false;
}
//Should we change the consist?
ImInts consist = ta.getTrain().getConsist();
if(!consist.equals(order.consist)){
// ..if so, we should change the consist.
int oldLength = ta.getTrain().getLength();
int engineType = ta.getTrain().getEngineType();
TrainModel newTrain = ta.getTrain().getNewInstance(engineType, order.consist);
worldDiffs.set(principal, KEY.TRAINS, trainId, newTrain);
int newLength = newTrain.getLength();
//has the trains length increased?
if(newLength > oldLength){
TrainMotion tm = ta.findCurrentMotion(Double.MAX_VALUE);
PathOnTiles path = tm.getPath();
path = lengthenPath(worldDiffs, path, oldLength);
SpeedTimeAndStatus.TrainActivity status = isWaiting4FullLoad() ? WAITING_FOR_FULL_LOAD : STOPPED_AT_STATION;
TrainMotion nextMotion = new TrainMotion(path, newLength,
0, status);
// Create a new Move object.
Move trainMove = new NextActivityMove(nextMotion, trainId,
principal);
MoveStatus ms = trainMove.doMove(worldDiffs, Player.AUTHORITATIVE);
if(!ms.ok) throw new IllegalStateException(ms.message);
}
}
/* Add any cargo that is waiting. */
loadAndUnloadCargo(schedule.getStationToGoto(), order.waitUntilFull, order.autoConsist);
//Should we stop waiting?
if(!order.waitUntilFull){
updateSchedule();
return false;
}
if (isTrainFull()) {
updateSchedule();
return false;
}
return true;
}
Outgoing Methods (calls):
jfreerails.controller.TrainStopsHandler.scheduledStop
Javadoc:
No Javadoc available
Method code:
private void scheduledStop() {
TrainModel train = (TrainModel) worldDiffs.get(principal, KEY.TRAINS, this.trainId);
Schedule schedule = (ImmutableSchedule) worldDiffs.get(principal, KEY.TRAIN_SCHEDULES,
train.getScheduleID());
ImInts wagonsToAdd = schedule.getWagonsToAdd();
// Loading and unloading cargo takes time, so we make the train wait for
// a few ticks.
makeTrainWait(50);
boolean autoConsist = schedule.autoConsist();
if (null != wagonsToAdd) {
int engine = train.getEngineType();
Move m = ChangeTrainMove.generateMove(this.trainId, train, engine, wagonsToAdd,
principal);
m.doMove(worldDiffs, principal);
}
updateSchedule();
int stationToGoto = schedule.getStationToGoto();
loadAndUnloadCargo(stationToGoto, true, autoConsist);
}
Outgoing Methods (calls):
jfreerails.controller.TrainStopsHandler.updateSchedule
Javadoc:
No Javadoc available
Method code:
void updateSchedule() {
TrainModel train = (TrainModel) worldDiffs.get(principal, KEY.TRAINS, this.trainId);
int scheduleID = train.getScheduleID();
ImmutableSchedule currentSchedule = (ImmutableSchedule) worldDiffs.get(principal,
KEY.TRAIN_SCHEDULES, scheduleID);
MutableSchedule schedule = new MutableSchedule(currentSchedule);
StationModel station = null;
TrainOrdersModel order = schedule.getOrder(schedule.getOrderToGoto());
boolean waiting4FullLoad = order.waitUntilFull && !isTrainFull();
if (!waiting4FullLoad) {
schedule.gotoNextStation();
ImmutableSchedule newSchedule = schedule.toImmutableSchedule();
worldDiffs.set(principal, KEY.TRAIN_SCHEDULES, scheduleID, newSchedule);
int stationNumber = schedule.getStationToGoto();
station = (StationModel) worldDiffs.get(principal, KEY.STATIONS, stationNumber);
if (null == station) {
logger.warning("null == station, train " + trainId
+ " doesn't know where to go next!");
}
}
}
Outgoing Methods (calls):
jfreerails.controller.TrainStopsHandler.updateTarget
Javadoc:
/** * Issues a ChangeTrainScheduleMove to set the train to move to the next * station. */
Method code:
/**
* Issues a ChangeTrainScheduleMove to set the train to move to the next
* station.
*/
public void updateTarget() {
scheduledStop();
}
Outgoing Methods (calls):
jfreerails.controller.TrainStopsHandlerTest.setup
Javadoc:
No Javadoc available
Method code:
@Before
public void setup() throws Exception {
MapCustomizer mc = new MapCustomizer();
ImPoint a = new ImPoint(10, 10);
ImPoint b = new ImPoint(20, 20);
mc.buildTrack(a, b).buildStation(a).buildStation(b);
mc.buildTrain(a, 0, 0);
w = mc.w;
}
Outgoing Methods (calls):
jfreerails.controller.TrainStopsHandlerTest.testWithEmptySchedule
Javadoc:
/** A train can have an empty schedule if all stops are removed from the * schedule or all the stations on the schedule are bulldozed. * * See bug #199 Unexpected Exception: null line -1 */
Method code:
/**
A train can have an empty schedule if all stops are removed from the
* schedule or all the stations on the schedule are bulldozed.
*
* See bug #199 Unexpected Exception: null line -1
*/
@Test
public void testWithEmptySchedule() {
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
assertEquals(2, w.size(principal, KEY.STATIONS));
assertEquals(1, w.size(principal, KEY.TRAINS));
WorldDiffs diffs = new WorldDiffs(w);
TrainStopsHandler tsh = new TrainStopsHandler(0, principal, diffs);
assertFalse(tsh.isWaiting4FullLoad());
ImmutableSchedule schedule = new MutableSchedule().toImmutableSchedule();
w.set(principal, KEY.TRAIN_SCHEDULES, 0, schedule);
boolean waiting4FullLoad = tsh.isWaiting4FullLoad();
assertFalse(waiting4FullLoad);
}
Outgoing Methods (calls):
jfreerails.controller.UnexpectedExceptionForm.closebuttonActionPerformed
Javadoc:
No Javadoc available
Method code:
private void closebuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closebuttonActionPerformed
System.exit(1);
}//GEN-LAST:event_closebuttonActionPerformed
No outgoing methods.
jfreerails.controller.UnexpectedExceptionForm.initComponents
Javadoc:
/** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */
Method code:
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
copyableTextJPanel1 = new jfreerails.controller.CopyableTextJPanel();
closebutton = new javax.swing.JButton();
getContentPane().setLayout(new java.awt.GridBagLayout());
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Unexpected Exception");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(copyableTextJPanel1, gridBagConstraints);
closebutton.setText("Close");
closebutton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closebuttonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
getContentPane().add(closebutton, gridBagConstraints);
pack();
}
Outgoing Methods (calls):
jfreerails.controller.UnexpectedExceptionForm.main
Javadoc:
/** * @param args the command line arguments */
Method code:
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
UnexpectedExceptionForm unexpectedExceptionForm = new UnexpectedExceptionForm();
Exception e = new Exception("Oh No..");
String str = ReportBugTextGenerator.genText(e);
unexpectedExceptionForm.setText(str);
unexpectedExceptionForm.setVisible(true);
e.printStackTrace();
}
});
}
Outgoing Methods (calls):
jfreerails.controller.UnexpectedExceptionForm.setText
Javadoc:
No Javadoc available
Method code:
public void setText(String s){
copyableTextJPanel1.setText(s);
}
Outgoing Methods (calls):
jfreerails.controller.VerifyStationName.checkStationExists
Javadoc:
No Javadoc available
Method code:
private boolean checkStationExists(String name) {
String testName = name;
StationModel tempStation;
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
while (wi.next()) { // loop over non null stations
tempStation = (StationModel) wi.getElement();
if ((testName).equals(tempStation.getStationName())) {
// station already exists with that name
return true;
}
}
}
// no stations exist with that name
return false;
}
Outgoing Methods (calls):
jfreerails.controller.VerifyStationName.getName
Javadoc:
No Javadoc available
Method code:
public String getName() {
String appropriateName = nameToVerify;
boolean found = false;
String tempName = null;
// if (w.size(KEY.STATIONS) <= 0) {
// //if there are no stations, then obviously the name isn't taken
// return appropriateName;
// }
found = checkStationExists(appropriateName);
if (!found) {
return appropriateName;
}
// a station with that name already exists, so we need to find another
// name
for (int i = 0; i < stationAlternatives.size(); i++) {
tempName = appropriateName + " " + stationAlternatives.elementAt(i);
found = checkStationExists(tempName);
if (!found) {
return tempName;
}
}
int j = 7; // for number of names that have already been used
while (found) {
j++;
tempName = appropriateName + "Station #" + j;
found = checkStationExists(tempName);
}
return tempName;
}
Outgoing Methods (calls):
jfreerails.controller.WagonLoad.compareTo
Javadoc:
No Javadoc available
Method code:
public int compareTo(WagonLoad test) {
return quantity - test.quantity;
}
No outgoing methods.
jfreerails.launcher.ClientOptionsJPanel.formComponentShown
Javadoc:
No Javadoc available
Method code:
private void formComponentShown(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_formComponentShown
validateInput();
}// GEN-LAST:event_formComponentShown
Outgoing Methods (calls):
jfreerails.launcher.ClientOptionsJPanel.fullScreenButtonStateChanged
Javadoc:
No Javadoc available
Method code:
private void fullScreenButtonStateChanged(javax.swing.event.ChangeEvent evt) {// GEN-FIRST:event_fullScreenButtonStateChanged
jList1.setEnabled(fullScreenButton.isSelected());
validateInput();
}// GEN-LAST:event_fullScreenButtonStateChanged
Outgoing Methods (calls):
jfreerails.launcher.ClientOptionsJPanel.getDisplayMode
Javadoc:
No Javadoc available
Method code:
DisplayMode getDisplayMode() {
if (this.fullScreenButton.isSelected()) {
MyDisplayMode displayMode = ((MyDisplayMode) jList1
.getSelectedValue());
logger.fine("The selected display mode is "
+ displayMode.toString());
return displayMode.displayMode;
}
return null;
}
Outgoing Methods (calls):
jfreerails.launcher.ClientOptionsJPanel.getPlayerName
Javadoc:
No Javadoc available
Method code:
String getPlayerName() {
if (playerName.isVisible()) {
return playerName.getText();
}
int index = playerNames.getSelectedIndex();
if (index < 0)
return null; // no selection.
return names[index];
}
No outgoing methods.
jfreerails.launcher.ClientOptionsJPanel.getRemoteServerAddress
Javadoc:
No Javadoc available
Method code:
InetSocketAddress getRemoteServerAddress() {
String portStr = remotePort.getText();
if (portStr == null) {
return null;
}
int port;
try {
port = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
return null;
}
InetSocketAddress address;
try {
address = new InetSocketAddress(remoteIP.getText(), port);
} catch (IllegalArgumentException e) {
return null;
}
/*
* cut and pasted InetSocketAddress isa = getRemoteServerAddress(); if
* (isa == null) { infoText = "Please enter a valid remote server
* address"; } else if (isa.isUnresolved()) { infoText = "Couldn't
* resolve remote server address"; } else { isValid = true; }
*/
return address;
}
No outgoing methods.
jfreerails.launcher.ClientOptionsJPanel.getScreenMode
Javadoc:
No Javadoc available
Method code:
int getScreenMode() {
if (this.fullScreenButton.isSelected()) {
return ScreenHandler.FULL_SCREEN;
} else if (this.windowedButton.isSelected()) {
return ScreenHandler.WINDOWED_MODE;
} else if (this.fixedSizeButton.isSelected()) {
return ScreenHandler.FIXED_SIZE_WINDOWED_MODE;
} else {
throw new IllegalStateException();
}
}
No outgoing methods.
jfreerails.launcher.ClientOptionsJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel3 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
playerName = new javax.swing.JTextField();
playerNames = new javax.swing.JComboBox();
jPanel4 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
remoteIP = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
remotePort = new javax.swing.JTextField();
spacer = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jPanel2 = new javax.swing.JPanel();
windowedButton = new javax.swing.JRadioButton();
fixedSizeButton = new javax.swing.JRadioButton();
fullScreenButton = new javax.swing.JRadioButton();
setLayout(new java.awt.GridBagLayout());
addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
jPanel3.setBorder(new javax.swing.border.TitledBorder(
new javax.swing.border.EtchedBorder(), "Player Details"));
jLabel1.setText("Player name:");
jPanel3.add(jLabel1);
playerName.setColumns(12);
playerName.setText(owner.getProperty("freerails.player.name"));
jPanel3.add(playerName);
playerNames.setToolTipText("Select a player from the saved game.");
jPanel3.add(playerNames);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
add(jPanel3, gridBagConstraints);
jPanel4.setLayout(new java.awt.GridBagLayout());
jPanel4
.setBorder(new javax.swing.border.TitledBorder(
new javax.swing.border.EtchedBorder(),
"Remote server address"));
jPanel4.setEnabled(false);
jLabel2.setText("IP Address:");
jPanel4.add(jLabel2, new java.awt.GridBagConstraints());
remoteIP.setColumns(15);
remoteIP.setText(owner.getProperty("freerails.server.ip.address"));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel4.add(remoteIP, gridBagConstraints);
jLabel3.setText("port");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel4.add(jLabel3, gridBagConstraints);
remotePort.setColumns(5);
remotePort.setText(owner.getProperty("freerails.server.port"));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel4.add(remotePort, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
jPanel4.add(spacer, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
add(jPanel4, gridBagConstraints);
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel1.setBorder(new javax.swing.border.TitledBorder(
new javax.swing.border.EtchedBorder(), "Select Display Mode"));
jScrollPane1.setBorder(new javax.swing.border.BevelBorder(
javax.swing.border.BevelBorder.LOWERED));
jList1
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.setEnabled(false);
jList1
.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(
javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jScrollPane1.setViewportView(jList1);
jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);
jPanel2.setLayout(new javax.swing.BoxLayout(jPanel2,
javax.swing.BoxLayout.Y_AXIS));
buttonGroup1.add(windowedButton);
windowedButton.setSelected(true);
windowedButton.setText("Windowed");
jPanel2.add(windowedButton);
buttonGroup1.add(fixedSizeButton);
fixedSizeButton.setText("Windowed (fixed size 640*480)");
jPanel2.add(fixedSizeButton);
buttonGroup1.add(fullScreenButton);
fullScreenButton.setText("Full screen");
fullScreenButton
.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
fullScreenButtonStateChanged(evt);
}
});
jPanel2.add(fullScreenButton);
jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jPanel1, gridBagConstraints);
}// GEN-END:initComponents
Outgoing Methods (calls):
jfreerails.launcher.ClientOptionsJPanel.jList1ValueChanged
Javadoc:
No Javadoc available
Method code:
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {// GEN-FIRST:event_jList1ValueChanged
validateInput();
}// GEN-LAST:event_jList1ValueChanged
Outgoing Methods (calls):
jfreerails.launcher.ClientOptionsJPanel.limitPlayerNames
Javadoc:
/** * If the user has opted to load a game, we need to limit the list of * players to participants in the game we are loading. Otherwise, any player * name is OK. Either, pass in a array of names or null if any name is OK. */
Method code:
/**
* If the user has opted to load a game, we need to limit the list of
* players to participants in the game we are loading. Otherwise, any player
* name is OK. Either, pass in a array of names or null if any name is OK.
*/
void limitPlayerNames(String[] n) {
this.names = n;
if (names == null) {
playerName.setVisible(true);
playerNames.setVisible(false);
playerName.setEditable(true);
} else {
if (names.length == 1) {
playerName.setVisible(true);
playerNames.setVisible(false);
playerName.setText(n[0]);
playerName.setEditable(false);
} else {
playerName.setVisible(false);
playerNames.setVisible(true);
ComboBoxModel model = new DefaultComboBoxModel(names);
playerNames.setModel(model);
}
}
this.revalidate();
}
No outgoing methods.
jfreerails.launcher.ClientOptionsJPanel.setControlsEnabled
Javadoc:
No Javadoc available
Method code:
public void setControlsEnabled(boolean enabled) {
windowedButton.setEnabled(enabled);
fullScreenButton.setEnabled(enabled);
fixedSizeButton.setEnabled(enabled);
if (fullScreenButton.isSelected()) {
jList1.setEnabled(enabled);
}
}
No outgoing methods.
jfreerails.launcher.ClientOptionsJPanel.setRemoteServerPanelVisible
Javadoc:
No Javadoc available
Method code:
void setRemoteServerPanelVisible(boolean b) {
this.jPanel4.setVisible(b);
}
No outgoing methods.
jfreerails.launcher.ClientOptionsJPanel.validateInput
Javadoc:
No Javadoc available
Method code:
public boolean validateInput() {
/* Validate player name. */
if (playerName.getText() == null || playerName.getText().equals("")) {
owner.setInfoText("Please set a name for your player",
LauncherInterface.ERROR);
return false;
}
/* Validate host name. */
if (remoteIP.getText() == null || remoteIP.getText().equals("")) {
owner.setInfoText("Please enter a host name",
LauncherInterface.ERROR);
return false;
}
/* Validate port. */
try {
int port = Integer.parseInt(remotePort.getText());
if (port < 0 || port > 65535) {
owner.setInfoText(INVALID_PORT, LauncherInterface.ERROR);
return false;
}
} catch (Exception e) {
owner.setInfoText(INVALID_PORT, LauncherInterface.ERROR);
return false;
}
/*
* Validate display-mode selection. Note, on some systems the display
* mode can't be changed, in which case the list of selectable display
* modes will have length 0.
*/
if (fullScreenButton.isSelected() && jList1.getModel().getSize() > 0
&& jList1.getSelectedIndex() == -1) {
owner
.setInfoText("Select a display-mode.",
LauncherInterface.ERROR);
return false;
}
/* Everything is ok. */
owner.hideErrorMessages();
owner.setProperty("freerails.server.port", this.remotePort.getText());
owner.setProperty("freerails.player.name", this.playerName.getText());
owner.setProperty("freerails.server.ip.address", this.remoteIP.getText());
owner.saveProps();
return true;
}
Outgoing Methods (calls):
jfreerails.launcher.ConnectedPlayersJPanel.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
title = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
setLayout(new java.awt.GridBagLayout());
title.setText("Connected Players");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(title, gridBagConstraints);
jList1.setModel(new javax.swing.AbstractListModel() {
private static final long serialVersionUID = 1L;
String[] strings = { "No players are logged on!" };
public int getSize() {
return strings.length;
}
public Object getElementAt(int i) {
return strings[i];
}
});
jScrollPane1.setViewportView(jList1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}// GEN-END:initComponents
No outgoing methods.
jfreerails.launcher.ConnectedPlayersJPanel.propertyChange
Javadoc:
/** Called by the server when a player is added or removed. */
Method code:
/** Called by the server when a player is added or removed. */
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(FreerailsGameServer.CONNECTED_PLAYERS)) {
if (EventQueue.isDispatchThread()) {
updateListOfPlayers();
} else {
EventQueue.invokeLater(new Runnable() {
public void run() {
updateListOfPlayers();
}
});
}
}
}
Outgoing Methods (calls):
jfreerails.launcher.ConnectedPlayersJPanel.setListOfPlayers
Javadoc:
No Javadoc available
Method code:
void setListOfPlayers(String[] players) {
jList1.setListData(players);
}
No outgoing methods.
jfreerails.launcher.ConnectedPlayersJPanel.updateListOfPlayers
Javadoc:
No Javadoc available
Method code:
void updateListOfPlayers() {
if (null != server) {
String[] playerNames = server.getPlayerNames();
playerNames = playerNames.length == 0 ? new String[] { "No players are logged on!" }
: playerNames;
setListOfPlayers(playerNames);
}
}
Outgoing Methods (calls):
jfreerails.launcher.GUIClient.clientUpdates
Javadoc:
No Javadoc available
Method code:
@Override
protected void clientUpdates() {
if (factory.isSetup()) {
factory.getBuildTrackController().update();
// Update sub tick time.
long currentTime = System.currentTimeMillis();
long lastTick = getLastTickTime();
double dt = currentTime - lastTick;
ReadOnlyWorld world2 = modelRoot.getWorld();
GameSpeed gameSpeed = (GameSpeed) world2.get(ITEM.GAME_SPEED);
GameTime currentGameTime = world2.currentTime();
double ticks = currentGameTime.getTicks();
if(!gameSpeed.isPaused()){
double milliSecondsPerTick = 1000/ gameSpeed.getSpeed();
double subTicks = dt / milliSecondsPerTick;
subTicks = Math.min(dt, 1d);
ticks += subTicks;
}
modelRoot.setProperty(Property.TIME, new Double(ticks));
}
}
Outgoing Methods (calls):
jfreerails.launcher.GUIClient.finished
Javadoc:
No Javadoc available
Method code:
public void finished() {
// TODO Auto-generated method stub
}
No outgoing methods.
jfreerails.launcher.GUIClient.getScreenHandler
Javadoc:
No Javadoc available
Method code:
public ScreenHandler getScreenHandler() {
return screenHandler;
}
No outgoing methods.
jfreerails.launcher.GUIClient.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
try {
GUIClient client = new GUIClient("Test", null,
ScreenHandler.WINDOWED_MODE, null);
client.start();
} catch (IOException e) {
e.printStackTrace();
}
}
Outgoing Methods (calls):
jfreerails.launcher.GUIClient.newWorld
Javadoc:
No Javadoc available
Method code:
@Override
protected void newWorld(World w) {
try {
if (null == vl || !vl.validate(w)) {
try {
vl = new RenderersRootImpl(w, monitor);
monitor.finished();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Should be a smarter way of doing this..
for (int player = 0; player < w.getNumberOfPlayers(); player++) {
Player p = w.getPlayer(player);
if (p.getName().equals(this.name)) {
modelRoot.setup(w, p.getPrincipal());
}
}
modelRoot.setProperty(ModelRoot.Property.SERVER, connection2Server
.getServerDetails());
actionRoot.setup(modelRoot, vl);
factory.setup(vl, w);
} catch (Exception e) {
ReportBugTextGenerator.unexpectedException(e);
}
}
Outgoing Methods (calls):
jfreerails.launcher.GUIClient.nextStep
Javadoc:
No Javadoc available
Method code:
public void nextStep(int max) {
// TODO Auto-generated method stub
}
No outgoing methods.
jfreerails.launcher.GUIClient.setMessage
Javadoc:
No Javadoc available
Method code:
public void setMessage(String s) {
System.out.println(s);
}
No outgoing methods.
jfreerails.launcher.GUIClient.setProperty
Javadoc:
No Javadoc available
Method code:
@Override
public void setProperty(ClientProperty propertyName, Serializable value) {
super.setProperty(propertyName, value);
switch (propertyName) {
case SAVED_GAMES:
modelRoot.setProperty(Property.SAVED_GAMES_LIST, value);
break;
default:
break;
}
}
Outgoing Methods (calls):
jfreerails.launcher.GUIClient.setValue
Javadoc:
No Javadoc available
Method code:
public void setValue(int i) {
// TODO Auto-generated method stub
}
No outgoing methods.
jfreerails.launcher.GUIClient.start
Javadoc:
/** * Initializes and starts the game by setting up the server, connecting to it, * creating a new game, and launching the game loop. * * This method performs the following steps: * 1. Sets up the game world and initializes the saved games manager. * 2. Creates and configures the FreerailsGameServer with the game model. * 3. Connects to the server using the provided name and password. * 4. Starts a new game with the selected map. * 5. Waits for the world to be initialized and updates the game state. * 6. Launches the game loop in a separate thread to handle ongoing updates. */
Method code:
void start() {
// Set up world.
SavedGamesManager gamesManager = new SavedGamesManagerImpl();
FreerailsGameServer server = new FreerailsGameServer(gamesManager);
String mapName = gamesManager.getNewMapNames()[0];
ServerGameModelImpl serverGameModel = new ServerGameModelImpl();
server.setServerGameModel(serverGameModel);
this.connect(server, name, "password");
server.newGame(mapName);
while (null == this.getWorld()) {
this.update();
server.update();
}
GameModel[] models = new GameModel[] { this, server };
// Start the game loop
GameLoop gameLoop = new GameLoop(screenHandler, models);
Thread t = new Thread(gameLoop);
t.start();
}
Outgoing Methods (calls):
jfreerails.launcher.Launcher.exit
Javadoc:
No Javadoc available
Method code:
private static void exit(Exception e) {
ReportBugTextGenerator.unexpectedException(e);
}
Outgoing Methods (calls):
jfreerails.launcher.Launcher.exitForm
Javadoc:
/** Exit the Application. */
Method code:
/** Exit the Application. */
private void exitForm(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_exitForm
System.exit(0);
}// GEN-LAST:event_exitForm
No outgoing methods.
jfreerails.launcher.Launcher.getProperty
Javadoc:
No Javadoc available
Method code:
public String getProperty(String key){
return props.getProperty(key);
}
No outgoing methods.
jfreerails.launcher.Launcher.hideAllMessages
Javadoc:
No Javadoc available
Method code:
public void hideAllMessages() {
infoLabel.setText(null);
infoLabel.setIcon(null);
nextButton.setEnabled(true);
}
No outgoing methods.
jfreerails.launcher.Launcher.hideErrorMessages
Javadoc:
No Javadoc available
Method code:
public void hideErrorMessages() {
if (infoLabel.getIcon() == errorIcon) {
infoLabel.setText(null);
infoLabel.setIcon(null);
nextButton.setEnabled(true);
}
}
No outgoing methods.
jfreerails.launcher.Launcher.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
nextButton = new javax.swing.JButton();
prevButton = new javax.swing.JButton();
infoLabel = new javax.swing.JLabel();
getContentPane().setLayout(new java.awt.GridBagLayout());
setTitle("Freerails Launcher");
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
jPanel1.setLayout(new java.awt.CardLayout());
jPanel1.setPreferredSize(new java.awt.Dimension(400, 300));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(jPanel1, gridBagConstraints);
nextButton.setText("Next...");
nextButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(nextButton, gridBagConstraints);
prevButton.setText("Back...");
prevButton.setEnabled(false);
prevButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
prevButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(prevButton, gridBagConstraints);
infoLabel.setText("Error messages go here!");
infoLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
infoLabel.setMinimumSize(new java.awt.Dimension(20, 20));
infoLabel.setPreferredSize(new java.awt.Dimension(20, 20));
infoLabel.setVerifyInputWhenFocusTarget(false);
infoLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(infoLabel, gridBagConstraints);
pack();
}// GEN-END:initComponents
Outgoing Methods (calls):
jfreerails.launcher.Launcher.initServer
Javadoc:
No Javadoc available
Method code:
private void initServer() {
SavedGamesManager gamesManager = new SavedGamesManagerImpl();
server = new FreerailsGameServer(gamesManager);
ServerGameModelImpl serverGameModel = new ServerGameModelImpl();
server.setServerGameModel(serverGameModel);
/*
* Set the server field on the connected players panel so that it can
* keep track of who is connected.
*/
ConnectedPlayersJPanel cp = (ConnectedPlayersJPanel) wizardPages[3];
cp.server = server;
server.addPropertyChangeListener(cp);
cp.updateListOfPlayers();
}
Outgoing Methods (calls):
jfreerails.launcher.Launcher.isNewGame
Javadoc:
No Javadoc available
Method code:
private boolean isNewGame() {
SelectMapJPanel msp2 = (SelectMapJPanel) wizardPages[1];
return msp2.getSelection().equals(SelectMapJPanel.Selection.NEW_GAME);
}
Outgoing Methods (calls):
jfreerails.launcher.Launcher.loadProps
Javadoc:
No Javadoc available
Method code:
private void loadProps(){
try{
props = new Properties();
FileInputStream in = new FileInputStream("freerails.properties");
props.load(in);
in.close();
if(!props.containsKey("freerails.server.port") ||
!props.containsKey("freerails.server.port") ||
!props.containsKey("freerails.server.port")){
throw new Exception();
}
}catch (Exception e){
props = new Properties();
props.setProperty("freerails.server.port", "55000");
props.setProperty("freerails.player.name", System.getProperty("user.name"));
props.setProperty("freerails.server.ip.address", "127.0.0.1");
}
}
No outgoing methods.
jfreerails.launcher.Launcher.main
Javadoc:
/** * Runs the game. */
Method code:
/**
* Runs the game.
*/
public static void main(String args[]) {
//SynchronizedEventQueue.use();
// Let the user know if we are using a custom logging config.
String loggingProperties = System
.getProperty("java.util.logging.config.file");
if (null != loggingProperties) {
logger.info("Logging properties file: " + loggingProperties);
}
logger.fine("Started launcher.");
boolean quickstart = false;
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (QUICKSTART.equals(args[i]))
quickstart = true;
}
}
Launcher launcher = new Launcher(quickstart);
launcher.start(quickstart);
}
Outgoing Methods (calls):
jfreerails.launcher.Launcher.nextButtonActionPerformed
Javadoc:
No Javadoc available
Method code:
private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_nextButtonActionPerformed
try {
CardLayout cl = (CardLayout) jPanel1.getLayout();
LauncherPanel1 panel = (LauncherPanel1) wizardPages[0];
SelectMapJPanel msp = (SelectMapJPanel) wizardPages[1];
ClientOptionsJPanel cop = (ClientOptionsJPanel) wizardPages[2];
hideAllMessages();
switch (currentPage) {
case 0:
msp.validateInput();
/* Initial game selection page */
switch (panel.getMode()) {
case LauncherPanel1.MODE_SERVER_ONLY:
/* go to map selection screen */
cl.next(jPanel1);
msp.setServerPortPanelVisible(true);
currentPage++;
break;
case LauncherPanel1.MODE_SINGLE_PLAYER:
/* go to map selection screen */
cl.next(jPanel1);
msp.setServerPortPanelVisible(false);
cop.setRemoteServerPanelVisible(false);
currentPage++;
break;
case LauncherPanel1.MODE_START_NETWORK_GAME:
/* go to map selection screen */
msp.setServerPortPanelVisible(true);
cop.setRemoteServerPanelVisible(false);
cl.next(jPanel1);
currentPage++;
break;
case LauncherPanel1.MODE_JOIN_NETWORK_GAME:
/* client display options */
nextIsStart = true;
cl.show(jPanel1, "2");
currentPage = 2;
msp.setServerPortPanelVisible(false);
cop.setRemoteServerPanelVisible(true);
cop.limitPlayerNames(null);
break;
}
prevButton.setEnabled(true);
break;
case 1:
/* map selection page */
if (panel.getMode() == LauncherPanel1.MODE_SERVER_ONLY) {
if (msp.validateInput()) {
prevButton.setEnabled(false);
try {
if (!isNewGame()) {
initServer();
server
.loadgame(ServerControlInterface.FREERAILS_SAV);
}
prepare2HostNetworkGame(msp.getServerPort());
} catch (BindException be) {
// When the port is already in use.
prevButton.setEnabled(true);
setInfoText(be.getMessage(),
LauncherInterface.WARNING);
}
}
} else {
if (isNewGame()) {
cop.limitPlayerNames(null);
} else {
initServer();
server.loadgame(msp.getSaveGameName());
String[] playernames = server.getPlayerNames();
cop.limitPlayerNames(playernames);
}
nextIsStart = true;
prevButton.setEnabled(true);
setNextEnabled(true);
currentPage++;
cl.next(jPanel1);
}
break;
case 2:
/* display mode selection */
if (panel.getMode() == LauncherPanel1.MODE_START_NETWORK_GAME) {
if (msp.validateInput()) {
prevButton.setEnabled(false);
int mode = cop.getScreenMode();
prepare2HostNetworkGame(msp.getServerPort());
client = new GUIClient(cop.getPlayerName(),
progressPanel, mode, cop.getDisplayMode());
client.connect(server, cop.getPlayerName(), "password");
}
} else {
prevButton.setEnabled(false);
cop.setControlsEnabled(false);
startGame();
}
break;
case 3:
try {
/* Connection status screen */
prevButton.setEnabled(false);
setServerGameModel();// TODO catch exception
if (panel.getMode() == LauncherPanel1.MODE_START_NETWORK_GAME) {
startThread(server, client);
cl.show(jPanel1, "4");
} else {
/* Start a stand alone server. */
startThread(server);
setVisible(false);
}
setButtonsVisible(false);
setNextEnabled(false);
} catch (IOException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setNextEnabled(true);
currentPage = 1;
cl.show(jPanel1, "1");
return;
}
break;
default:
throw new IllegalArgumentException(String.valueOf(currentPage));
}
} catch (Exception e) {
exit(e);
}
}// GEN-LAST:event_nextButtonActionPerformed
Outgoing Methods (calls):
jfreerails.launcher.Launcher.prepare2HostNetworkGame
Javadoc:
/** Starts a thread listening for new connections. */
Method code:
/** Starts a thread listening for new connections. */
private void prepare2HostNetworkGame(int port) throws IOException {
loadProps();
if (isNewGame()) {
initServer();
}
InetConnectionAccepter accepter = new InetConnectionAccepter(port,
server);
/*
* Note, the thread's name gets set in the run method so there is no
* point setting it here.
*/
Thread t = new Thread(accepter);
t.start();
CardLayout cl = (CardLayout) jPanel1.getLayout();
cl.show(jPanel1, "3");
currentPage = 3;
}
Outgoing Methods (calls):
jfreerails.launcher.Launcher.prevButtonActionPerformed
Javadoc:
No Javadoc available
Method code:
private void prevButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_prevButtonActionPerformed
CardLayout cl = (CardLayout) jPanel1.getLayout();
nextIsStart = false;
hideAllMessages();
switch (currentPage) {
case 1:
cl.previous(jPanel1);
currentPage--;
prevButton.setEnabled(false);
break;
case 2:
LauncherPanel1 panel = (LauncherPanel1) wizardPages[0];
if (panel.getMode() == LauncherPanel1.MODE_JOIN_NETWORK_GAME) {
currentPage = 0;
cl.show(jPanel1, "0");
prevButton.setEnabled(false);
} else {
currentPage--;
cl.previous(jPanel1);
}
}
}// GEN-LAST:event_prevButtonActionPerformed
Outgoing Methods (calls):
jfreerails.launcher.Launcher.saveProps
Javadoc:
No Javadoc available
Method code:
public void saveProps(){
try{
FileOutputStream out = new FileOutputStream("freerails.properties");
props.store(out, "---No Comment---");
out.close();
//Copy key-value pairs to System.Properties so
//that they are visible in the game via the
//show java properties menu item.
System.getProperties().putAll(props);
}catch (Exception e){
logger.warning(e.getMessage());
}
}
No outgoing methods.
jfreerails.launcher.Launcher.setButtonsVisible
Javadoc:
No Javadoc available
Method code:
public void setButtonsVisible(boolean b){
nextButton.setVisible(b);
prevButton.setVisible(b);
}
No outgoing methods.
jfreerails.launcher.Launcher.setInfoText
Javadoc:
No Javadoc available
Method code:
public void setInfoText(String text, int status) {
infoLabel.setText(text);
switch (status) {
case LauncherInterface.ERROR:
infoLabel.setIcon(errorIcon);
nextButton.setEnabled(false);
break;
case LauncherInterface.INFO:
infoLabel.setIcon(infoIcon);
nextButton.setEnabled(true);
break;
case LauncherInterface.WARNING:
infoLabel.setIcon(warningIcon);
nextButton.setEnabled(true);
break;
default:
throw new IllegalArgumentException(String.valueOf(status));
}
}
No outgoing methods.
jfreerails.launcher.Launcher.setNextEnabled
Javadoc:
No Javadoc available
Method code:
public void setNextEnabled(boolean enabled) {
nextButton.setEnabled(enabled);
if (nextIsStart) {
nextButton.setText("Start");
} else {
nextButton.setText("Next...");
}
}
No outgoing methods.
jfreerails.launcher.Launcher.setProperty
Javadoc:
No Javadoc available
Method code:
public void setProperty(String key, String value){
props.setProperty(key, value);
}
No outgoing methods.
jfreerails.launcher.Launcher.setServerGameModel
Javadoc:
No Javadoc available
Method code:
private void setServerGameModel() throws IOException {
ClientOptionsJPanel cop = (ClientOptionsJPanel) wizardPages[2];
if (isNewGame()) {
SelectMapJPanel msp2 = (SelectMapJPanel) wizardPages[1];
server.newGame(msp2.getNewMapName());
cop.limitPlayerNames(null);
} else {
// Do nothing since the server is already set up.
}
}
Outgoing Methods (calls):
jfreerails.launcher.Launcher.start
Javadoc:
/** * Shows GUI. If <code>quickstart</code> is <code>true</code> runs the * game. * * @param quickstart * boolean */
Method code:
/**
* Shows GUI. If <code>quickstart</code> is <code>true</code> runs the
* game.
*
* @param quickstart
* boolean
*/
public void start(boolean quickstart) {
setVisible(true);
if (quickstart) {
startGame();
}
}
Outgoing Methods (calls):
jfreerails.launcher.Launcher.startGame
Javadoc:
No Javadoc available
Method code:
private void startGame() {
CardLayout cl = (CardLayout) jPanel1.getLayout();
cl.show(jPanel1, "4");
setButtonsVisible(false);
LauncherPanel1 lp = (LauncherPanel1) wizardPages[0];
SelectMapJPanel msp = (SelectMapJPanel) wizardPages[1];
ClientOptionsJPanel cop = (ClientOptionsJPanel) wizardPages[2];
ConnectedPlayersJPanel cp = (ConnectedPlayersJPanel) wizardPages[3];
boolean recover = false;
int mode;
switch (lp.getMode()) {
case LauncherPanel1.MODE_SINGLE_PLAYER:
try {
mode = cop.getScreenMode();
client = new GUIClient(cop.getPlayerName(), progressPanel,
mode, cop.getDisplayMode());
if (isNewGame()) {
initServer();
}
client.connect(server, cop.getPlayerName(), "password");
setServerGameModel();
} catch (IOException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} finally {
if (recover) {
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setButtonsVisible(true);
currentPage = 1;
cl.show(jPanel1, "1");
return;
}
}
startThread(server, client);
break;
case LauncherPanel1.MODE_START_NETWORK_GAME:
// LL: I don't think this code ever executes now that there is a
// connected players screen.
try {
setServerGameModel();
currentPage = 3;
String[] playerNames = server.getPlayerNames();
playerNames = playerNames.length == 0 ? new String[] { "No players are connected." }
: playerNames;
cp.setListOfPlayers(playerNames);
cl.show(jPanel1, "3");
setNextEnabled(false);
} catch (IOException e) {
// We end up here if an Exception was thrown when loading a
// saved game.
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} finally {
if (recover) {
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setNextEnabled(true);
currentPage = 1;
setButtonsVisible(true);
cl.show(jPanel1, "1");
return;
}
}
break;
case LauncherPanel1.MODE_JOIN_NETWORK_GAME:
mode = cop.getScreenMode();
try {
InetSocketAddress serverInetAddress = cop
.getRemoteServerAddress();
if (null == serverInetAddress) {
throw new NullPointerException("Couldn't resolve hostname.");
}
String playerName = cop.getPlayerName();
client = new GUIClient(playerName, progressPanel, mode, cop
.getDisplayMode());
String hostname = serverInetAddress.getHostName();
int port = serverInetAddress.getPort();
setInfoText("Connecting to server...", LauncherInterface.INFO);
LogOnResponse logOnResponse = client.connect(hostname, port,
playerName, "password");
if (logOnResponse.isSuccessful()) {
setInfoText("Logged on and waiting for game to start.", LauncherInterface.INFO);
startThread(client);
} else {
recover = true;
setInfoText(logOnResponse.getMessage(),
LauncherInterface.WARNING);
}
} catch (IOException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} catch (NullPointerException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} finally {
if (recover) {
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setButtonsVisible(true);
cl.show(jPanel1, "2");
return;
}
}
break;
case LauncherPanel1.MODE_SERVER_ONLY:
if (msp.validateInput()) {
initServer();
try {
setServerGameModel();
prepare2HostNetworkGame(msp.getServerPort());
setNextEnabled(true);
} catch (NullPointerException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} catch (IOException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} finally {
if (recover) {
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setButtonsVisible(true);
return;
}
}
}
}// End of switch statement
}
Outgoing Methods (calls):
jfreerails.launcher.Launcher.startThread
Javadoc:
/** Starts the client and server in the same thread. */
Method code:
/** Starts the client and server in the same thread. */
private static void startThread(final FreerailsGameServer server,
final GUIClient client) {
try {
Runnable run = new Runnable() {
public void run() {
while (null == client.getWorld()) {
client.update();
server.update();
}
GameModel[] models = new GameModel[] { client, server };
ScreenHandler screenHandler = client.getScreenHandler();
GameLoop gameLoop = new GameLoop(screenHandler, models);
//screenHandler.apply();
gameLoop.run();
}
};
Thread t = new Thread(run, "Client + server main loop");
t.start();
} catch (Exception e) {
exit(e);
}
}
Outgoing Methods (calls):
jfreerails.launcher.LauncherInterface.getProperty
Javadoc:
No Javadoc available
Method code:
String getProperty(String key);
No outgoing methods.
jfreerails.launcher.LauncherInterface.hideAllMessages
Javadoc:
No Javadoc available
Method code:
void hideAllMessages();
No outgoing methods.
jfreerails.launcher.LauncherInterface.hideErrorMessages
Javadoc:
No Javadoc available
Method code:
void hideErrorMessages();
No outgoing methods.
jfreerails.launcher.LauncherInterface.saveProps
Javadoc:
No Javadoc available
Method code:
void saveProps();
No outgoing methods.
jfreerails.launcher.LauncherInterface.setInfoText
Javadoc:
No Javadoc available
Method code:
void setInfoText(String text, int status);
No outgoing methods.
jfreerails.launcher.LauncherInterface.setNextEnabled
Javadoc:
No Javadoc available
Method code:
void setNextEnabled(boolean enabled);
No outgoing methods.
jfreerails.launcher.LauncherInterface.setProperty
Javadoc:
No Javadoc available
Method code:
void setProperty(String key, String value);
No outgoing methods.
jfreerails.launcher.LauncherPanel.validateInput
Javadoc:
No Javadoc available
Method code:
boolean validateInput();
No outgoing methods.
jfreerails.launcher.LauncherPanel1.getMode
Javadoc:
No Javadoc available
Method code:
int getMode() {
for (int i = 0; i < buttonModels.length; i++) {
if (buttonGroup1.getSelection() == buttonModels[i]) {
return i;
}
}
assert false;
return 0;
}
No outgoing methods.
jfreerails.launcher.LauncherPanel1.initComponents
Javadoc:
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
Method code:
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup1 = new javax.swing.ButtonGroup();
singlePlayerButton = new javax.swing.JRadioButton();
startNetworkButton = new javax.swing.JRadioButton();
joinNetworkButton = new javax.swing.JRadioButton();
serverOnlyButton = new javax.swing.JRadioButton();
paddingJPanel = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
setBorder(new javax.swing.border.TitledBorder(
new javax.swing.border.EtchedBorder(), "Select Game Type"));
buttonGroup1.add(singlePlayerButton);
singlePlayerButton.setSelected(true);
singlePlayerButton.setText("Single-Player");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(singlePlayerButton, gridBagConstraints);
buttonGroup1.add(startNetworkButton);
startNetworkButton.setText("Start a network game");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(startNetworkButton, gridBagConstraints);
buttonGroup1.add(joinNetworkButton);
joinNetworkButton.setText("Join a network game");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(joinNetworkButton, gridBagConstraints);
buttonGroup1.add(serverOnlyButton);
serverOnlyButton.setText("Server only");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(serverOnlyButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(paddingJPanel, gridBagConstraints);
}// GEN-END:initComponents
No outgoing methods.
jfreerails.launcher.ProgressJPanel.finished
Javadoc:
No Javadoc available
Method code:
public void finished() {
if(numSteps-1 != step)
throw new IllegalStateException(numSteps +"!="+ step);
getTopLevelAncestor().setVisible(false);
}
No outgoing methods.
jfreerails.launcher.ProgressJPanel.initComponents
Javadoc:
/** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */
Method code:
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
progressBar = new javax.swing.JProgressBar();
splashImage = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(3, 7, 3, 7);
add(progressBar, gridBagConstraints);
splashImage.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
splashImage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jfreerails/client/graphics/splash_screen.jpg")));
add(splashImage, new java.awt.GridBagConstraints());
}
No outgoing methods.
jfreerails.launcher.ProgressJPanel.nextStep
Javadoc:
No Javadoc available
Method code:
public void nextStep(int max) {
//So that the waiting for game to start message
//goes away.
owner.hideAllMessages();
step++;
stepSize = max;
if(numSteps < step)
throw new IllegalStateException();
}
Outgoing Methods (calls):
jfreerails.launcher.ProgressJPanel.setValue
Javadoc:
No Javadoc available
Method code:
public void setValue(int i) {
int value = i * 100 / stepSize;
value += 100 * step;
progressBar.setValue(value);
}
No outgoing methods.
jfreerails.launcher.SelectMapJPanel.getNewMapName
Javadoc:
No Javadoc available
Method code:
public String getNewMapName() {
return (String) newmapsJList.getSelectedValue();
}
No outgoing methods.
jfreerails.launcher.SelectMapJPanel.getSaveGameName
Javadoc:
No Javadoc available
Method code:
public String getSaveGameName() {
return (String) savedmapsJList.getSelectedValue();
}
No outgoing methods.
jfreerails.launcher.SelectMapJPanel.getSelection
Javadoc:
No Javadoc available
Method code:
Selection getSelection() {
if( newmapsJList.getSelectedIndex() != -1 ){
savedmapsJList.setSelectedIndex(-1);
return Selection.NEW_GAME;
}
if(savedmapsJList.getSelectedIndex() != -1){
return Selection.LOAD_GAME;
}
return Selection.NONE;
}
No outgoing methods.
jfreerails.launcher.SelectMapJPanel.getServerPort
Javadoc:
No Javadoc available
Method code:
int getServerPort() {
String s = serverPort.getText();
return Integer.parseInt(s);
}
No outgoing methods.
jfreerails.launcher.SelectMapJPanel.initComponents
Javadoc:
/** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */
Method code:
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
newmapsJList = new javax.swing.JList();
jPanel4 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
savedmapsJList = new javax.swing.JList();
jPanel3 = new javax.swing.JPanel();
portLabel = new javax.swing.JLabel();
serverPort = new javax.swing.JTextField();
jPanel2 = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel1.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), "New Game"));
jPanel1.setPreferredSize(null);
jScrollPane1.setViewportBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
newmapsJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
newmapsJList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
newmapsJListValueChanged(evt);
}
});
jScrollPane1.setViewportView(newmapsJList);
jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jPanel1, gridBagConstraints);
jPanel4.setLayout(new java.awt.BorderLayout());
jPanel4.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), "Load game"));
jPanel4.setPreferredSize(null);
jPanel4.setRequestFocusEnabled(false);
jScrollPane2.setViewportBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
savedmapsJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
savedmapsJList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
savedmapsJListValueChanged(evt);
}
});
jScrollPane2.setViewportView(savedmapsJList);
jPanel4.add(jScrollPane2, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jPanel4, gridBagConstraints);
jPanel3.setLayout(new java.awt.GridBagLayout());
jPanel3.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), "Server port"));
portLabel.setText("Port:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel3.add(portLabel, gridBagConstraints);
serverPort.setColumns(6);
serverPort.setText( owner.getProperty("freerails.server.port"));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel3.add(serverPort, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
jPanel3.add(jPanel2, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
add(jPanel3, gridBagConstraints);
}
Outgoing Methods (calls):
jfreerails.launcher.SelectMapJPanel.newmapsJListValueChanged
Javadoc:
No Javadoc available
Method code:
private void newmapsJListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_newmapsJListValueChanged
if(newmapsJList.getSelectedIndex() != -1)
savedmapsJList.clearSelection();
validateInput();
}//GEN-LAST:event_newmapsJListValueChanged
Outgoing Methods (calls):
jfreerails.launcher.SelectMapJPanel.savedmapsJListValueChanged
Javadoc:
No Javadoc available
Method code:
private void savedmapsJListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_savedmapsJListValueChanged
if(savedmapsJList.getSelectedIndex() != -1)
newmapsJList.clearSelection();
validateInput();
}//GEN-LAST:event_savedmapsJListValueChanged
Outgoing Methods (calls):
jfreerails.launcher.SelectMapJPanel.setServerPortPanelVisible
Javadoc:
/** * Sets the visibility of the server port panel. * * @param b {@code true} to show the server port panel, {@code false} to hide it */
Method code:
void setServerPortPanelVisible(boolean b) {
this.jPanel3.setVisible(b);
}
No outgoing methods.
jfreerails.launcher.SelectMapJPanel.validateInput
Javadoc:
No Javadoc available
Method code:
public boolean validateInput() {
/* Validate map selection. */
if (this.getSelection().equals(Selection.NONE)) {
owner.setInfoText(SELECT_A_MAP, LauncherInterface.ERROR);
return false;
}
/* Validate port. */
try {
int port = getServerPort();
if (port < 0 || port > 65535) {
owner.setInfoText(INVALID_PORT, LauncherInterface.ERROR);
return false;
}
} catch (Exception e) {
owner.setInfoText(INVALID_PORT, LauncherInterface.ERROR);
return false;
}
/* Everything is ok. */
owner.hideErrorMessages();
owner.setProperty("freerails.server.port", this.serverPort.getText());
owner.saveProps();
return true;
}
Outgoing Methods (calls):
jfreerails.launcher.Unknown.changedUpdate
Javadoc:
No Javadoc available
Method code:
public void changedUpdate(DocumentEvent e) {
validateInput();
}
Outgoing Methods (calls):
jfreerails.launcher.Unknown.insertUpdate
Javadoc:
No Javadoc available
Method code:
public void insertUpdate(DocumentEvent e) {
validateInput();
}
Outgoing Methods (calls):
jfreerails.launcher.Unknown.removeUpdate
Javadoc:
No Javadoc available
Method code:
public void removeUpdate(DocumentEvent e) {
validateInput();
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.assertDoMoveFails
Javadoc:
No Javadoc available
Method code:
protected void assertDoMoveFails(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.doMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertTrue("Move went through when it should have failed", !ms.ok);
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.assertDoMoveIsOk
Javadoc:
No Javadoc available
Method code:
protected void assertDoMoveIsOk(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.doMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals(MoveStatus.MOVE_OK, ms);
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.assertDoThenUndoLeavesWorldUnchanged
Javadoc:
No Javadoc available
Method code:
protected void assertDoThenUndoLeavesWorldUnchanged(Move m) {
try {
World w = getWorld();
World before = (World) Utils.cloneBySerialisation(w);
assertEquals(before, w);
assertTrue(m.doMove(w, Player.AUTHORITATIVE).ok);
World after = (World) Utils.cloneBySerialisation(w);
assertFalse(after.equals(before));
boolean b = m.undoMove(w, Player.AUTHORITATIVE).ok;
assertTrue(b);
assertEquals(before, w);
} catch (Exception e) {
e.printStackTrace();
assertTrue(false);
}
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.assertOkAndRepeatable
Javadoc:
No Javadoc available
Method code:
protected void assertOkAndRepeatable(Move m) {
assertSetupHasBeenCalled();
// Do move
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
// Since it leaves the world unchanged it should also be
// possible to undo it repeatably
assertTryUndoMoveIsOk(m);
assertUndoMoveIsOk(m);
assertTryUndoMoveIsOk(m);
assertUndoMoveIsOk(m);
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.assertOkButNotRepeatable
Javadoc:
/** * Generally moves should not be repeatable. For example, if we have just * removed a piece of track, that piece of track is gone, so we cannot * remove it again. */
Method code:
/**
* Generally moves should not be repeatable. For example, if we have just
* removed a piece of track, that piece of track is gone, so we cannot
* remove it again.
*/
protected void assertOkButNotRepeatable(Move m) {
assertSetupHasBeenCalled();
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
assertTryMoveFails(m);
assertDoMoveFails(m);
assertTryUndoMoveIsOk(m);
assertUndoMoveIsOk(m);
assertTryUndoMoveFails(m);
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.assertSetupHasBeenCalled
Javadoc:
No Javadoc available
Method code:
private void assertSetupHasBeenCalled() {
assertTrue("AbstractMoveTestCase.setUp has not been called!",
hasSetupBeenCalled());
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.assertSurvivesSerialisation
Javadoc:
/** * This method asserts that if we serialise then deserialize the specified * move, the specified move is equal to the deserialized move. The assertion * depends on the move being serializable and the equals method being * implemented correctly. Also checks that the hashcode does not change. * * @param m */
Method code:
/**
* This method asserts that if we serialise then deserialize the specified
* move, the specified move is equal to the deserialized move. The assertion
* depends on the move being serializable and the equals method being
* implemented correctly. Also checks that the hashcode does not change.
*
* @param m
*/
protected void assertSurvivesSerialisation(FreerailsSerializable m) {
assertEquals("Reflexivity violated: the move does not equal itself", m,
m);
try {
Object o = Utils.cloneBySerialisation(m);
assertEquals(m, o);
assertEquals("The hashcodes should be the same!", m.hashCode(), o
.hashCode());
} catch (Exception e) {
e.printStackTrace();
assertTrue(false);
}
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.assertTrackHere
Javadoc:
No Javadoc available
Method code:
protected void assertTrackHere(int x, int y) {
FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
assertTrue(tile.hasTrack());
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.assertTryMoveFails
Javadoc:
No Javadoc available
Method code:
protected void assertTryMoveFails(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertTrue("Move went through when it should have failed", !ms.ok);
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.assertTryMoveIsOk
Javadoc:
No Javadoc available
Method code:
protected void assertTryMoveIsOk(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals("First try failed", MoveStatus.MOVE_OK, ms);
ms = m.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals(
"Second try failed, this suggests that the tryDoMove method failed to leave the world unchanged!",
MoveStatus.MOVE_OK, ms);
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.assertTryUndoMoveFails
Javadoc:
No Javadoc available
Method code:
protected void assertTryUndoMoveFails(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryUndoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertTrue("Move went through when it should have failed", !ms.ok);
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.assertTryUndoMoveIsOk
Javadoc:
No Javadoc available
Method code:
protected void assertTryUndoMoveIsOk(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryUndoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals("First try failed", MoveStatus.MOVE_OK, ms);
ms = m.tryUndoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals(
"Second try failed, this suggests that the tryDoMove method failed to leave the world unchanged!",
MoveStatus.MOVE_OK, ms);
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.assertUndoMoveFails
Javadoc:
No Javadoc available
Method code:
protected void assertUndoMoveFails(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryUndoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertTrue("Move went through when it should have failed", !ms.ok);
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.assertUndoMoveIsOk
Javadoc:
No Javadoc available
Method code:
protected void assertUndoMoveIsOk(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.undoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals(MoveStatus.MOVE_OK, ms);
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.getPrincipal
Javadoc:
No Javadoc available
Method code:
FreerailsPrincipal getPrincipal() {
return world.getPlayer(0).getPrincipal();
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.getWorld
Javadoc:
No Javadoc available
Method code:
World getWorld() {
return world;
}
No outgoing methods.
jfreerails.move.AbstractMoveTestCase.hasSetupBeenCalled
Javadoc:
No Javadoc available
Method code:
protected boolean hasSetupBeenCalled() {
return hasSetupBeenCalled;
}
No outgoing methods.
jfreerails.move.AbstractMoveTestCase.setHasSetupBeenCalled
Javadoc:
No Javadoc available
Method code:
protected void setHasSetupBeenCalled(boolean hasSetupBeenCalled) {
this.hasSetupBeenCalled = hasSetupBeenCalled;
}
No outgoing methods.
jfreerails.move.AbstractMoveTestCase.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
setHasSetupBeenCalled(true);
setupWorld();
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.setWorld
Javadoc:
No Javadoc available
Method code:
void setWorld(World world) {
this.world = world;
}
No outgoing methods.
jfreerails.move.AbstractMoveTestCase.setupWorld
Javadoc:
No Javadoc available
Method code:
protected void setupWorld() {
setWorld(new WorldImpl(10, 10));
// Set the time..
getWorld().set(ITEM.CALENDAR, new GameCalendar(12000, 1840));
getWorld().addPlayer(MapFixtureFactory.TEST_PLAYER);
}
Outgoing Methods (calls):
jfreerails.move.AbstractMoveTestCase.testMove
Javadoc:
No Javadoc available
Method code:
public void testMove(){}
No outgoing methods.
jfreerails.move.AddActiveEntityMove.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.ok)
w.addActiveEntity(principal, activity);
return ms;
}
Outgoing Methods (calls):
jfreerails.move.AddActiveEntityMove.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (index != w.size(principal))
return MoveStatus.moveFailed("index != w.size(listKey, p)");
return MoveStatus.MOVE_OK;
}
Outgoing Methods (calls):
jfreerails.move.AddActiveEntityMove.tryUndoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int expectedSize = index + 1;
if (expectedSize != w.size(principal))
return MoveStatus
.moveFailed("(index + 1) != w.size(listKey, principal)");
ActivityIterator ai = w.getActivities(principal, index);
if (ai.hasNext())
return MoveStatus
.moveFailed("There should be exactly one activity!");
Activity act = ai.getActivity();
if (!act.equals(activity))
return MoveStatus.moveFailed("Expected " + activity.toString()
+ " but found " + act.toString());
return MoveStatus.MOVE_OK;
}
Outgoing Methods (calls):
jfreerails.move.AddActiveEntityMove.undoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.ok)
w.removeLastActiveEntity(principal);
return ms;
}
Outgoing Methods (calls):
jfreerails.move.AddActiveEntityMoveTest.testMove
Javadoc:
No Javadoc available
Method code:
@Override
public void testMove() {
FreerailsPrincipal p = getPrincipal();
Activity a = new WorldImplTest.TestActivity(50);
AddActiveEntityMove move = new AddActiveEntityMove(a, 0,
p);
assertSurvivesSerialisation(move);
assertOkButNotRepeatable(move);
AddActiveEntityMove move2 = new AddActiveEntityMove(a, 2,
p);
assertTryMoveFails(move2);
}
Outgoing Methods (calls):
jfreerails.move.AddCargoBundleMoveTest.testMove
Javadoc:
No Javadoc available
Method code:
@Override
public void testMove() {
MutableCargoBundle bundleA;
MutableCargoBundle bundleB;
bundleA = new MutableCargoBundle();
bundleB = new MutableCargoBundle();
bundleA.setAmount(new CargoBatch(1, 2, 3, 4, 0), 5);
bundleB.setAmount(new CargoBatch(1, 2, 3, 4, 0), 5);
assertEquals(bundleA, bundleB);
Move m = new AddCargoBundleMove(0, bundleA.toImmutableCargoBundle(),
MapFixtureFactory.TEST_PRINCIPAL);
assertDoMoveIsOk(m);
assertEquals(getWorld().size(MapFixtureFactory.TEST_PRINCIPAL,
KEY.CARGO_BUNDLES), 1);
assertUndoMoveIsOk(m);
assertSurvivesSerialisation(m);
assertOkButNotRepeatable(m);
}
Outgoing Methods (calls):
jfreerails.move.AddItemToListMove.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.isOk()) {
w.add(this.principal, listKey, this.item);
}
return ms;
}
Outgoing Methods (calls):
jfreerails.move.AddItemToListMove.getAfter
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable getAfter() {
return item;
}
No outgoing methods.
jfreerails.move.AddItemToListMove.getBefore
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable getBefore() {
return null;
}
No outgoing methods.
jfreerails.move.AddItemToListMove.getIndex
Javadoc:
No Javadoc available
Method code:
public int getIndex() {
return index;
}
No outgoing methods.
jfreerails.move.AddItemToListMove.getKey
Javadoc:
No Javadoc available
Method code:
public KEY getKey() {
return listKey;
}
No outgoing methods.
jfreerails.move.AddItemToListMove.getPrincipal
Javadoc:
No Javadoc available
Method code:
public FreerailsPrincipal getPrincipal() {
return principal;
}
No outgoing methods.
jfreerails.move.AddItemToListMove.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.size(this.principal, listKey) != index) {
return MoveStatus.moveFailed("Expected size of "
+ listKey.toString() + " list is " + index
+ " but actual size is " + w.size(this.principal, listKey));
}
return MoveStatus.MOVE_OK;
}
Outgoing Methods (calls):
jfreerails.move.AddItemToListMove.tryUndoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int expectListSize = index + 1;
if (w.size(this.principal, listKey) != expectListSize) {
return MoveStatus.moveFailed("Expected size of "
+ listKey.toString() + " list is " + expectListSize
+ " but actual size is " + w.size(this.principal, listKey));
}
return MoveStatus.MOVE_OK;
}
Outgoing Methods (calls):
jfreerails.move.AddItemToListMove.undoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.isOk()) {
w.removeLast(this.principal, listKey);
}
return ms;
}
Outgoing Methods (calls):
jfreerails.move.AddItemToSharedListMove.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.isOk()) {
w.add(listKey, this.item);
}
return ms;
}
Outgoing Methods (calls):
jfreerails.move.AddItemToSharedListMove.getAfter
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable getAfter() {
return item;
}
No outgoing methods.
jfreerails.move.AddItemToSharedListMove.getBefore
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable getBefore() {
return null;
}
No outgoing methods.
jfreerails.move.AddItemToSharedListMove.getIndex
Javadoc:
No Javadoc available
Method code:
public int getIndex() {
return index;
}
No outgoing methods.
jfreerails.move.AddItemToSharedListMove.getKey
Javadoc:
No Javadoc available
Method code:
public SKEY getKey() {
return listKey;
}
No outgoing methods.
jfreerails.move.AddItemToSharedListMove.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.size(listKey) != index) {
return MoveStatus.moveFailed("Expected size of "
+ listKey.toString() + " list is " + index
+ " but actual size is " + w.size(listKey));
}
return MoveStatus.MOVE_OK;
}
Outgoing Methods (calls):
jfreerails.move.AddItemToSharedListMove.tryUndoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int expectListSize = index + 1;
if (w.size(listKey) != expectListSize) {
return MoveStatus.moveFailed("Expected size of "
+ listKey.toString() + " list is " + expectListSize
+ " but actual size is " + w.size(listKey));
}
return MoveStatus.MOVE_OK;
}
Outgoing Methods (calls):
jfreerails.move.AddItemToSharedListMove.undoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.isOk()) {
w.removeLast(listKey);
}
return ms;
}
Outgoing Methods (calls):
jfreerails.move.AddPlayerMove.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (!ms.ok)
return ms;
int playerId = w.addPlayer(this.player2add);
// Sell the player 2 $500,000 bonds at 5% interest.
FreerailsPrincipal principal = player2add.getPrincipal();
w.addTransaction(principal, BondTransaction.issueBond(5));
//Issue stock
Money initialStockPrice = new Money(5);
Transaction t = StockTransaction.issueStock(playerId, 100000,
initialStockPrice);
w.addTransaction(principal, t);
return ms;
}
Outgoing Methods (calls):
jfreerails.move.AddPlayerMove.generateMove
Javadoc:
No Javadoc available
Method code:
public static AddPlayerMove generateMove(ReadOnlyWorld w, Player player) {
/**
* create a new player with a corresponding Principal
*/
Player player2add = new Player(player.getName(), w.getNumberOfPlayers());
return new AddPlayerMove(player2add);
}
Outgoing Methods (calls):
jfreerails.move.AddPlayerMove.isAlreadyASimilarPlayer
Javadoc:
No Javadoc available
Method code:
private boolean isAlreadyASimilarPlayer(World w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
Player pp = w.getPlayer(i);
if (pp.getName().equalsIgnoreCase(this.player2add.getName())) {
return true;
}
}
return false;
}
Outgoing Methods (calls):
jfreerails.move.AddPlayerMove.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (isAlreadyASimilarPlayer(w))
return MoveStatus
.moveFailed("There is already a player with the same name.");
return MoveStatus.MOVE_OK;
}
Outgoing Methods (calls):
jfreerails.move.AddPlayerMove.tryUndoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int numPlayers = w.getNumberOfPlayers();
Player pp = w.getPlayer(numPlayers - 1);
if (pp.equals(player2add)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("The last player is " + pp.getName()
+ "not " + player2add.getName());
}
Outgoing Methods (calls):
jfreerails.move.AddPlayerMove.undoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (!ms.ok)
return ms;
w.removeLastTransaction(player2add.getPrincipal());
w.removeLastTransaction(player2add.getPrincipal());
w.removeLastPlayer();
return ms;
}
Outgoing Methods (calls):
jfreerails.move.AddPlayerMoveTest.testMove
Javadoc:
No Javadoc available
Method code:
@Override
public void testMove() {
Player newPlayer = new Player("New Player");
assertTrue("Check reflexivity of Player.equals(.)", Utils
.equalsBySerialization(newPlayer, newPlayer));
AddPlayerMove move = AddPlayerMove.generateMove(getWorld(), newPlayer);
assertSurvivesSerialisation(move);
assertDoThenUndoLeavesWorldUnchanged(move);
}
Outgoing Methods (calls):
jfreerails.move.AddPlayerMoveTest.testMove2
Javadoc:
No Javadoc available
Method code:
public void testMove2() {
Player newPlayer = new Player("New Player");
AddPlayerMove move = AddPlayerMove.generateMove(getWorld(), newPlayer);
assertOkButNotRepeatable(move);
}
Outgoing Methods (calls):
jfreerails.move.AddStationMove.generateMove
Javadoc:
No Javadoc available
Method code:
public static AddStationMove generateMove(ReadOnlyWorld w,
String stationName, ImPoint p,
ChangeTrackPieceMove upgradeTrackMove, FreerailsPrincipal principal) {
int cargoBundleNumber = w.size(principal, KEY.CARGO_BUNDLES);
Move addCargoBundleMove = new AddCargoBundleMove(cargoBundleNumber,
ImmutableCargoBundle.EMPTY_BUNDLE, principal);
int stationNumber = w.size(principal, KEY.STATIONS);
StationModel station = new StationModel(p.x, p.y, stationName, w
.size(SKEY.CARGO_TYPES), cargoBundleNumber);
Move addStation = new AddItemToListMove(KEY.STATIONS, stationNumber,
station, principal);
return new AddStationMove(new Move[] { upgradeTrackMove,
addCargoBundleMove, addStation });
}
Outgoing Methods (calls):
jfreerails.move.AddStationMove.getNewStation
Javadoc:
No Javadoc available
Method code:
public StationModel getNewStation() {
AddItemToListMove addStation = (AddItemToListMove) super.getMove(2);
return (StationModel) addStation.getAfter();
}
Outgoing Methods (calls):
jfreerails.move.AddStationMove.upgradeStation
Javadoc:
No Javadoc available
Method code:
public static AddStationMove upgradeStation(
ChangeTrackPieceMove upgradeTrackMove) {
return new AddStationMove(new Move[] { upgradeTrackMove });
}
No outgoing methods.
jfreerails.move.AddTransactionMove.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.ok) {
w.addTransaction(this.principal, this.transaction);
}
return ms;
}
Outgoing Methods (calls):
jfreerails.move.AddTransactionMove.getPrincipal
Javadoc:
No Javadoc available
Method code:
public FreerailsPrincipal getPrincipal() {
return principal;
}
No outgoing methods.
jfreerails.move.AddTransactionMove.getTransaction
Javadoc:
No Javadoc available
Method code:
public Transaction getTransaction() {
return transaction;
}
No outgoing methods.
jfreerails.move.AddTransactionMove.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.isPlayer(principal)) {
if (this.constrained) {
long bankBalance = w.getCurrentBalance(principal).getAmount();
long transactionAmount = this.transaction.deltaCash()
.getAmount();
long balanceAfter = bankBalance + transactionAmount;
if (transactionAmount < 0 && balanceAfter < 0) {
return MoveStatus.moveFailed("You can't afford that!");
}
}
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed(p.getName()
+ " does not have a bank account.");
}
Outgoing Methods (calls):
jfreerails.move.AddTransactionMove.tryUndoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int size = w.getNumberOfTransactions(this.principal);
if (0 == size) {
return MoveStatus.moveFailed("No transactions to remove!");
}
Transaction lastTransaction = w
.getTransaction(this.principal, size - 1);
if (lastTransaction.equals(this.transaction)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + this.transaction
+ "but found " + lastTransaction);
}
Outgoing Methods (calls):
jfreerails.move.AddTransactionMove.undoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.ok) {
w.removeLastTransaction(this.principal);
}
return ms;
}
Outgoing Methods (calls):
jfreerails.move.AddTransactionMoveTest.testConstrainedMove
Javadoc:
No Javadoc available
Method code:
public void testConstrainedMove() {
Money currentBalance = getWorld().getCurrentBalance(
MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(new Money(0), currentBalance);
Transaction t = new Bill(new Money(100),
Transaction.Category.MISC_INCOME);
Move m = new AddTransactionMove(MapFixtureFactory.TEST_PRINCIPAL, t,
true);
// This move should fail since there is no money in the account and
// it is constrained is set to true.
assertTryMoveFails(m);
}
Outgoing Methods (calls):
jfreerails.move.AddTransactionMoveTest.testMove
Javadoc:
No Javadoc available
Method code:
@Override
public void testMove() {
Money currentBalance = getWorld().getCurrentBalance(
MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(new Money(0), currentBalance);
Transaction t = new Receipt(new Money(100),
Transaction.Category.MISC_INCOME);
Move m = new AddTransactionMove(MapFixtureFactory.TEST_PRINCIPAL, t);
assertTryMoveIsOk(m);
assertTryUndoMoveFails(m);
assertDoMoveIsOk(m);
currentBalance = getWorld().getCurrentBalance(
MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(new Money(100), currentBalance);
final Player PLAYER_WITHOUT_ACCOUNT = new Player(
"PLAYER_WITHOUT_ACCOUNT", 4);
assertSurvivesSerialisation(m);
Move m2 = new AddTransactionMove(PLAYER_WITHOUT_ACCOUNT.getPrincipal(),
t);
assertTryMoveFails(m2);
assertOkAndRepeatable(m);
}
Outgoing Methods (calls):
jfreerails.move.ChangeCargoBundleMoveTest.testMove
Javadoc:
No Javadoc available
Method code:
@Override
public void testMove() {
MutableCargoBundle before;
MutableCargoBundle after;
before = new MutableCargoBundle();
after = new MutableCargoBundle();
before.setAmount(new CargoBatch(1, 2, 3, 4, 0), 5);
after.setAmount(new CargoBatch(1, 2, 3, 4, 0), 8);
Move m = new ChangeCargoBundleMove(before.toImmutableCargoBundle(),
after.toImmutableCargoBundle(), 0,
MapFixtureFactory.TEST_PRINCIPAL);
assertSurvivesSerialisation(m);
assertTryMoveFails(m);
assertTryUndoMoveFails(m);
getWorld().add(MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES,
before.toImmutableCargoBundle());
}
Outgoing Methods (calls):
jfreerails.move.ChangeGameSpeedMove.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryDoMove(w, p);
if (status.ok) {
w.set(ITEM.GAME_SPEED, newSpeed);
}
return status;
}
Outgoing Methods (calls):
jfreerails.move.ChangeGameSpeedMove.getMove
Javadoc:
No Javadoc available
Method code:
public static ChangeGameSpeedMove getMove(ReadOnlyWorld w,
GameSpeed newGameSpeed) {
return new ChangeGameSpeedMove((GameSpeed) w.get(ITEM.GAME_SPEED),
newGameSpeed);
}
Outgoing Methods (calls):
jfreerails.move.ChangeGameSpeedMove.getNewSpeed
Javadoc:
No Javadoc available
Method code:
public int getNewSpeed() {
return newSpeed.getSpeed();
}
Outgoing Methods (calls):
jfreerails.move.ChangeGameSpeedMove.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.get(ITEM.GAME_SPEED).equals(oldSpeed)) {
return MoveStatus.MOVE_OK;
}
String string = "oldSpeed = " + oldSpeed.getSpeed() + " <=> "
+ "currentSpeed "
+ ((GameSpeed) w.get(ITEM.GAME_SPEED)).getSpeed();
return MoveStatus.moveFailed(string);
}
Outgoing Methods (calls):
jfreerails.move.ChangeGameSpeedMove.tryUndoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
GameSpeed speed = ((GameSpeed) w.get(ITEM.GAME_SPEED));
if (speed.equals(newSpeed)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + newSpeed + ", found "
+ speed);
}
Outgoing Methods (calls):
jfreerails.move.ChangeGameSpeedMove.undoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryUndoMove(w, p);
if (status.isOk()) {
w.set(ITEM.GAME_SPEED, oldSpeed);
}
return status;
}
Outgoing Methods (calls):
jfreerails.move.ChangeItemInListMove.beforeEqualsAfter
Javadoc:
No Javadoc available
Method code:
public boolean beforeEqualsAfter(){
return Utils.equal(this.before, this.after);
}
Outgoing Methods (calls):
jfreerails.move.ChangeItemInListMove.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(World w, FreerailsPrincipal p) {
return move(after, before, w);
}
Outgoing Methods (calls):
jfreerails.move.ChangeItemInListMove.getAfter
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable getAfter() {
return after;
}
No outgoing methods.
jfreerails.move.ChangeItemInListMove.getBefore
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable getBefore() {
return before;
}
No outgoing methods.
jfreerails.move.ChangeItemInListMove.getIndex
Javadoc:
No Javadoc available
Method code:
public int getIndex() {
return index;
}
No outgoing methods.
jfreerails.move.ChangeItemInListMove.getKey
Javadoc:
No Javadoc available
Method code:
public KEY getKey() {
return listKey;
}
No outgoing methods.
jfreerails.move.ChangeItemInListMove.getPrincipal
Javadoc:
No Javadoc available
Method code:
public FreerailsPrincipal getPrincipal() {
return principal;
}
No outgoing methods.
jfreerails.move.ChangeItemInListMove.move
Javadoc:
No Javadoc available
Method code:
protected MoveStatus move(FreerailsSerializable to,
FreerailsSerializable from, World w) {
MoveStatus ms = tryMove(to, from, w);
if (ms.ok) {
w.set(principal, listKey, index, to);
}
return ms;
}
Outgoing Methods (calls):
jfreerails.move.ChangeItemInListMove.tryDoMove
Javadoc:
/** * Attempts to perform the move operation by invoking the internal tryMove method. * This method is responsible for executing the change of an item in a list within the game world. * * @param w The current game world state used to apply the move. * @param p The principal (user) associated with the move operation. * @return The status of the move operation indicating success, failure, or partial success. */
Method code:
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
return tryMove(after, before, w);
}
Outgoing Methods (calls):
jfreerails.move.ChangeItemInListMove.tryMove
Javadoc:
No Javadoc available
Method code:
protected MoveStatus tryMove(FreerailsSerializable to,
FreerailsSerializable from, World w) {
if (index >= w.size(principal, listKey)) {
return MoveStatus.moveFailed("w.size(listKey) is "
+ w.size(principal, listKey) + " but index is " + index);
}
FreerailsSerializable item2change = w.get(principal, listKey, index);
if (null == item2change) {
if (null == from) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected null but found " + from);
}
if (!from.equals(item2change)) {
String message = "Expected " + from.toString() + " but found "
+ to.toString();
return MoveStatus.moveFailed(message);
}
return MoveStatus.MOVE_OK;
}
Outgoing Methods (calls):
jfreerails.move.ChangeItemInListMove.tryUndoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
return tryMove(before, after, w);
}
Outgoing Methods (calls):
jfreerails.move.ChangeItemInListMove.undoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
return move(before, after, w);
}
Outgoing Methods (calls):
jfreerails.move.ChangeProductionAtEngineShopMove.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryDoMove(w, p);
if (status.isOk()) {
StationModel station = (StationModel) w.get(principal,
KEY.STATIONS, stationNumber);
station = new StationModel(station, this.after);
w.set(principal, KEY.STATIONS, stationNumber, station);
}
return status;
}
Outgoing Methods (calls):
jfreerails.move.ChangeProductionAtEngineShopMove.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
return tryMove(w, before);
}
Outgoing Methods (calls):
jfreerails.move.ChangeProductionAtEngineShopMove.tryMove
Javadoc:
No Javadoc available
Method code:
private MoveStatus tryMove(World w, ImList<PlannedTrain> stateA) {
// Check that the specified station exists.
if (!w.boundsContain(principal, KEY.STATIONS, this.stationNumber)) {
return MoveStatus.moveFailed(this.stationNumber + " " + principal);
}
StationModel station = (StationModel) w.get(principal, KEY.STATIONS,
stationNumber);
if (null == station) {
return MoveStatus.moveFailed(this.stationNumber + " " + principal
+ " is does null");
}
// Check that the station is building what we expect.
if (null == station.getProduction()) {
if (null == stateA) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed(this.stationNumber + " " + principal);
}
if (station.getProduction().equals(stateA)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed(this.stationNumber + " " + principal);
}
Outgoing Methods (calls):
jfreerails.move.ChangeProductionAtEngineShopMove.tryUndoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
return tryMove(w, after);
}
Outgoing Methods (calls):
jfreerails.move.ChangeProductionAtEngineShopMove.undoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryUndoMove(w, p);
if (status.isOk()) {
StationModel station = (StationModel) w.get(principal,
KEY.STATIONS, stationNumber);
station = new StationModel(station, this.before);
w.set(principal, KEY.STATIONS, stationNumber, station);
}
return status;
}
Outgoing Methods (calls):
jfreerails.move.ChangeProductionAtEngineShopMoveTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
super.setUp();
getWorld().add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
new StationModel());
getWorld().add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
new StationModel());
getWorld().add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
new StationModel());
WagonAndEngineTypesFactory wetf = new WagonAndEngineTypesFactory();
wetf.addTypesToWorld(getWorld());
engineType = 0;
wagonType = 0;
wagons = new int[] { wagonType, wagonType };
after = new ImList<PlannedTrain>(new PlannedTrain(
engineType, wagons));
}
Outgoing Methods (calls):
jfreerails.move.ChangeProductionAtEngineShopMoveTest.testMove
Javadoc:
No Javadoc available
Method code:
@Override
public void testMove() {
before = new ImList<PlannedTrain>();
ChangeProductionAtEngineShopMove m;
// Should fail because current production at station 0 is null;
m = new ChangeProductionAtEngineShopMove(after, before, 0,
MapFixtureFactory.TEST_PRINCIPAL);
assertTryMoveFails(m);
assertDoMoveFails(m);
// Should fail because station 6 does not exist.
m = new ChangeProductionAtEngineShopMove(before, after, 6,
MapFixtureFactory.TEST_PRINCIPAL);
assertTryMoveFails(m);
assertDoMoveFails(m);
// Should go through
m = new ChangeProductionAtEngineShopMove(before, after, 0,
MapFixtureFactory.TEST_PRINCIPAL);
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
assertTryUndoMoveIsOk(m);
assertUndoMoveIsOk(m);
// It should not be repeatable.
assertOkButNotRepeatable(m);
assertSurvivesSerialisation(m);
}
Outgoing Methods (calls):
jfreerails.move.ChangeProductionAtEngineShopMoveTest.testProductionAtEngineShopEquals
Javadoc:
No Javadoc available
Method code:
public void testProductionAtEngineShopEquals() {
PlannedTrain b;
PlannedTrain c;
b = new PlannedTrain(engineType, wagons);
c = new PlannedTrain(engineType, wagons);
assertEquals(c, b);
assertEquals(b, c);
}
No outgoing methods.
jfreerails.move.ChangeTileMove.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.isOk()) {
w.setTile(x, y, after);
}
return ms;
}
Outgoing Methods (calls):
jfreerails.move.ChangeTileMove.getUpdatedTiles
Javadoc:
/** * Returns the rectangle representing the single tile that has been updated by this move. * * @return the Rectangle object representing the updated tile's position and size (1x1). */
Method code:
public Rectangle getUpdatedTiles() {
Rectangle r = new Rectangle(x, y, 1, 1);
return r;
}
No outgoing methods.
jfreerails.move.ChangeTileMove.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
FreerailsTile actual = (FreerailsTile) w.getTile(x, y);
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES, actual
.getTerrainTypeID());
if (!type.getCategory().equals(TerrainType.Category.Country)) {
return MoveStatus.moveFailed("Can only build on clear terrain.");
}
if (actual.equals(before)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + before + " but found "
+ actual);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTileMove.tryUndoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
FreerailsTile actual = (FreerailsTile) w.getTile(x, y);
if (actual.equals(after)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + after + " but found "
+ actual);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTileMove.undoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.isOk()) {
w.setTile(x, y, before);
}
return ms;
}
Outgoing Methods (calls):
jfreerails.move.ChangeTileMoveTest.setupWorld
Javadoc:
No Javadoc available
Method code:
@Override
protected void setupWorld() {
world = MapFixtureFactory2.getCopy();
}
Outgoing Methods (calls):
jfreerails.move.ChangeTileMoveTest.testMove
Javadoc:
No Javadoc available
Method code:
@Override
public void testMove() {
Point p = new Point(10, 10);
TerrainTile tile = (TerrainTile) world.getTile(10, 10);
assertTrue(tile.getTerrainTypeID() != 5);
ChangeTileMove move = new ChangeTileMove(world, p, 5);
MoveStatus ms = move.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.message, ms.ok);
tile = (TerrainTile) world.getTile(10, 10);
assertTrue(tile.getTerrainTypeID() == 5);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTileMoveTest.testMove2
Javadoc:
No Javadoc available
Method code:
public void testMove2() {
Point p = new Point(10, 10);
ChangeTileMove move = new ChangeTileMove(world, p, 5);
assertSurvivesSerialisation(move);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMove.compositeTest
Javadoc:
No Javadoc available
Method code:
@Override
protected MoveStatus compositeTest(World world, FreerailsPrincipal p) {
if (mustConnectToExistingTrack(world)) {
if (hasAnyTrackBeenBuilt(world, this.builder)) {
try {
ChangeTrackPieceMove a = (ChangeTrackPieceMove) super
.getMove(0);
ChangeTrackPieceMove b = (ChangeTrackPieceMove) super
.getMove(1);
int ruleBeforeA = a.trackPieceBefore.getTrackTypeID();
int ruleBeforeB = b.trackPieceBefore.getTrackTypeID();
if (ruleBeforeA == NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER
&& ruleBeforeB == NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
return MoveStatus
.moveFailed("Must connect to existing track");
}
} catch (ClassCastException e) {
// It was not the type of move we expected.
// We end up here when we are removing a station.
return MoveStatus.MOVE_OK;
}
}
}
return MoveStatus.MOVE_OK;
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMove.findRuleID
Javadoc:
No Javadoc available
Method code:
public static int findRuleID(TrackRule r, ReadOnlyWorld w) {
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
Object o = w.get(SKEY.TRACK_RULES, i);
if (r.equals(o)) {
return i;
}
}
throw new IllegalStateException();
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMove.generateBuildTrackMove
Javadoc:
No Javadoc available
Method code:
public static ChangeTrackPieceCompositeMove generateBuildTrackMove(
ImPoint from, Step direction, TrackRule ruleA, TrackRule ruleB,
ReadOnlyWorld w, FreerailsPrincipal principal) {
ChangeTrackPieceMove a;
ChangeTrackPieceMove b;
a = getBuildTrackChangeTrackPieceMove(from, direction, ruleA, w,
principal);
b = getBuildTrackChangeTrackPieceMove(direction
.createRelocatedPoint(from), direction.getOpposite(), ruleB, w,
principal);
return new ChangeTrackPieceCompositeMove(a, b, principal);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMove.generateRemoveTrackMove
Javadoc:
No Javadoc available
Method code:
public static ChangeTrackPieceCompositeMove generateRemoveTrackMove(
ImPoint from, Step direction, ReadOnlyWorld w,
FreerailsPrincipal principal) throws Exception {
TrackMove a;
TrackMove b;
a = getRemoveTrackChangeTrackPieceMove(from, direction, w, principal);
b = getRemoveTrackChangeTrackPieceMove(direction
.createRelocatedPoint(from), direction.getOpposite(), w,
principal);
return new ChangeTrackPieceCompositeMove(a, b, principal);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMove.getBuildTrackChangeTrackPieceMove
Javadoc:
No Javadoc available
Method code:
// utility method.
private static ChangeTrackPieceMove getBuildTrackChangeTrackPieceMove(
ImPoint p, Step direction, TrackRule trackRule, ReadOnlyWorld w,
FreerailsPrincipal principal) {
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
int owner = getOwner(principal, w);
if (w.boundsContain(p.x, p.y)) {
oldTrackPiece = ((FreerailsTile) w.getTile(p.x, p.y))
.getTrackPiece();
if (oldTrackPiece.getTrackRule() != NullTrackType.getInstance()) {
TrackConfiguration trackConfiguration = TrackConfiguration.add(
oldTrackPiece.getTrackConfiguration(), direction);
newTrackPiece = new TrackPieceImpl(trackConfiguration,
oldTrackPiece.getTrackRule(), owner, oldTrackPiece
.getTrackTypeID());
} else {
newTrackPiece = getTrackPieceWhenOldTrackPieceIsNull(direction,
trackRule, owner, findRuleID(trackRule, w));
}
} else {
newTrackPiece = getTrackPieceWhenOldTrackPieceIsNull(direction,
trackRule, owner, findRuleID(trackRule, w));
oldTrackPiece = NullTrackPiece.getInstance();
}
return new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece, p);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMove.getOwner
Javadoc:
No Javadoc available
Method code:
public static int getOwner(FreerailsPrincipal p, ReadOnlyWorld w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
if (w.getPlayer(i).getPrincipal().equals(p)) {
return i;
}
}
throw new IllegalStateException();
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMove.getRemoveTrackChangeTrackPieceMove
Javadoc:
No Javadoc available
Method code:
// utility method.
private static TrackMove getRemoveTrackChangeTrackPieceMove(ImPoint p,
Step direction, ReadOnlyWorld w, FreerailsPrincipal principal)
throws Exception {
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
if (w.boundsContain(p.x, p.y)) {
oldTrackPiece = ((FreerailsTile) w.getTile(p.x, p.y)).getTrackPiece();
if (oldTrackPiece.getTrackRule() != NullTrackType.getInstance()) {
TrackConfiguration trackConfiguration = TrackConfiguration
.subtract(oldTrackPiece.getTrackConfiguration(),
direction);
if (trackConfiguration != TrackConfiguration
.getFlatInstance("000010000")) {
int owner = getOwner(principal, w);
newTrackPiece = new TrackPieceImpl(trackConfiguration,
oldTrackPiece.getTrackRule(), owner, oldTrackPiece
.getTrackTypeID());
} else {
newTrackPiece = NullTrackPiece.getInstance();
}
} else {
// There is no track to remove.
// Fix for bug [ 948670 ] Removing non-existent track
throw new Exception();
}
} else {
newTrackPiece = NullTrackPiece.getInstance();
oldTrackPiece = NullTrackPiece.getInstance();
}
ChangeTrackPieceMove m = new ChangeTrackPieceMove(oldTrackPiece,
newTrackPiece, p);
// If we are removing a station, we also need to remove the station from
// the station list.
if (oldTrackPiece.getTrackRule().isStation()
&& !newTrackPiece.getTrackRule().isStation()) {
return RemoveStationMove.getInstance(w, m, principal);
}
return m;
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMove.getTrackPieceWhenOldTrackPieceIsNull
Javadoc:
No Javadoc available
Method code:
private static TrackPiece getTrackPieceWhenOldTrackPieceIsNull(
Step direction, TrackRule trackRule, int owner, int ruleNumber) {
TrackConfiguration simplestConfig = TrackConfiguration
.getFlatInstance("000010000");
TrackConfiguration trackConfiguration = TrackConfiguration.add(
simplestConfig, direction);
return new TrackPieceImpl(trackConfiguration, trackRule, owner,
ruleNumber);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMove.getUpdatedTiles
Javadoc:
No Javadoc available
Method code:
public Rectangle getUpdatedTiles() {
return new Rectangle(x, y, w, h);
}
No outgoing methods.
jfreerails.move.ChangeTrackPieceCompositeMove.hasAnyTrackBeenBuilt
Javadoc:
/** Returns true if some track has been built. */
Method code:
/** Returns true if some track has been built. */
static boolean hasAnyTrackBeenBuilt(ReadOnlyWorld world,
FreerailsPrincipal principal) {
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
world, principal);
aggregator.setCategory(Transaction.Category.TRACK);
return aggregator.calculateQuantity() > 0;
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMove.mustConnectToExistingTrack
Javadoc:
No Javadoc available
Method code:
private static boolean mustConnectToExistingTrack(ReadOnlyWorld world) {
GameRules rules = (GameRules) world.get(ITEM.GAME_RULES);
return rules.isMustConnect2ExistingTrack();
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMoveTest.assertBuildTrackFails
Javadoc:
No Javadoc available
Method code:
private void assertBuildTrackFails(ImPoint p, Step v, TrackRule rule) {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(p, v, rule, rule, getWorld(),
MapFixtureFactory.TEST_PRINCIPAL);
MoveStatus status = move.doMove(getWorld(), Player.AUTHORITATIVE);
assertEquals(false, status.isOk());
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMoveTest.assertBuildTrackSucceeds
Javadoc:
No Javadoc available
Method code:
private void assertBuildTrackSucceeds(ImPoint p, Step v, TrackRule rule) {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(p, v, rule, rule, getWorld(),
MapFixtureFactory.TEST_PRINCIPAL);
Move moveAndTransaction = transactionsGenerator.addTransactions(move);
MoveStatus status = moveAndTransaction.doMove(getWorld(),
Player.AUTHORITATIVE);
assertEquals(true, status.isOk());
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMoveTest.assertRemoveTrackSucceeds
Javadoc:
No Javadoc available
Method code:
private void assertRemoveTrackSucceeds(ImPoint p, Step v) {
try {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateRemoveTrackMove(p, v, getWorld(),
MapFixtureFactory.TEST_PRINCIPAL);
MoveStatus status = move.doMove(getWorld(), Player.AUTHORITATIVE);
assertEquals(true, status.isOk());
} catch (Exception e) {
fail();
}
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMoveTest.main
Javadoc:
No Javadoc available
Method code:
public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMoveTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() {
super.setHasSetupBeenCalled(true);
setWorld(new WorldImpl(10, 10));
getWorld().set(ITEM.GAME_RULES, GameRules.DEFAULT_RULES);
getWorld().addPlayer(MapFixtureFactory.TEST_PLAYER);
MapFixtureFactory.generateTrackRuleList(getWorld());
transactionsGenerator = new TrackMoveTransactionsGenerator(getWorld(),
MapFixtureFactory.TEST_PRINCIPAL);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMoveTest.suite
Javadoc:
No Javadoc available
Method code:
public static Test suite() {
TestSuite testSuite = new TestSuite(
ChangeTrackPieceCompositeMoveTest.class);
return testSuite;
}
No outgoing methods.
jfreerails.move.ChangeTrackPieceCompositeMoveTest.testBuildTrack
Javadoc:
No Javadoc available
Method code:
public void testBuildTrack() {
ImPoint pointA = new ImPoint(0, 0);
ImPoint pointB = new ImPoint(1, 1);
ImPoint pointC = new ImPoint(1, 0);
TrackRule trackRule = (TrackRule) getWorld().get(SKEY.TRACK_RULES, 0);
// First track piece built
assertBuildTrackSucceeds(pointA, southeast, trackRule);
// Track connected from one existing track piece
assertBuildTrackSucceeds(pointB, northeast, trackRule);
// Track connected to one existing track piece
// This is not going through for some reason, not sure why.
// assertBuildTrackSucceeds(pointC, west, trackRule);
// Track connecting two existing track pieces.
assertBuildTrackSucceeds(pointA, east, trackRule);
// Track off map.. should fail.
assertBuildTrackFails(pointA, northeast, trackRule);
// Track already there.
assertBuildTrackFails(pointA, southeast, trackRule);
// Illegal config. connecting from one existing track piece
assertBuildTrackFails(pointA, south, trackRule);
// Illegal config. connecting to one existing track piece
assertBuildTrackFails(new ImPoint(0, 1), northeast, trackRule);
// Illegal config. connecting between two existing track pieces
assertBuildTrackFails(pointC, south, trackRule);
// Not allowed on this terrain type, from existing track.
assertBuildTrackFails(new ImPoint(2, 0), northeast,
(TrackRule) getWorld().get(SKEY.TRACK_RULES, 1));
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMoveTest.testCannotConnect2OtherRRsTrack
Javadoc:
No Javadoc available
Method code:
public void testCannotConnect2OtherRRsTrack() {
assertFalse(ChangeTrackPieceMove.canConnect2OtherRRsTrack(world));
final int TRACK_RULE_ID = 0;
TrackRule trackRule = (TrackRule) getWorld().get(SKEY.TRACK_RULES,
TRACK_RULE_ID);
assertBuildTrackSucceeds(new ImPoint(0, 6), east, trackRule);
// Now change the owner of the track piece at (1, 6);
int anotherPlayer = 999;
FreerailsTile oldTile = (FreerailsTile) world.getTile(1, 6);
TrackPiece tp = oldTile.getTrackPiece();
TrackPiece newTrackPiece = new TrackPieceImpl(tp
.getTrackConfiguration(), tp.getTrackRule(), anotherPlayer,
TRACK_RULE_ID);
FreerailsTile newTile = FreerailsTile.getInstance(oldTile
.getTerrainTypeID(), newTrackPiece);
world.setTile(1, 6, newTile);
assertBuildTrackFails(new ImPoint(1, 6), east, trackRule);
world.setTile(1, 6, oldTile);
assertBuildTrackSucceeds(new ImPoint(1, 6), east, trackRule);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMoveTest.testMove
Javadoc:
No Javadoc available
Method code:
@Override
public void testMove() {
ImPoint pointA = new ImPoint(0, 0);
TrackRule trackRule = (TrackRule) getWorld().get(SKEY.TRACK_RULES, 0);
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(pointA, southeast, trackRule,
trackRule, getWorld(), MapFixtureFactory.TEST_PRINCIPAL);
assertSurvivesSerialisation(move);
assertOkButNotRepeatable(move);
setUp();
assertDoThenUndoLeavesWorldUnchanged(move);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMoveTest.testMustConnect2ExistingTrack
Javadoc:
/** * All track except the first piece built should be connected to existing * track. */
Method code:
/**
* All track except the first piece built should be connected to existing
* track.
*/
public void testMustConnect2ExistingTrack() {
TrackRule trackRule = (TrackRule) world.get(SKEY.TRACK_RULES, 0);
int numberOfTransactions = world
.getNumberOfTransactions(MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(0, numberOfTransactions);
boolean hasTrackBeenBuilt = ChangeTrackPieceCompositeMove
.hasAnyTrackBeenBuilt(world, MapFixtureFactory.TEST_PRINCIPAL);
assertFalse("No track has been built yet.", hasTrackBeenBuilt);
assertBuildTrackSucceeds(new ImPoint(0, 5), east, trackRule);
// Building the track should have added a transaction.
numberOfTransactions = world
.getNumberOfTransactions(MapFixtureFactory.TEST_PRINCIPAL);
assertTrue(0 < numberOfTransactions);
hasTrackBeenBuilt = ChangeTrackPieceCompositeMove.hasAnyTrackBeenBuilt(
world, MapFixtureFactory.TEST_PRINCIPAL);
assertTrue("One track piece has been built.", hasTrackBeenBuilt);
assertBuildTrackSucceeds(new ImPoint(1, 5), east, trackRule);
assertBuildTrackFails(new ImPoint(4, 8), east, trackRule);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceCompositeMoveTest.testRemoveTrack
Javadoc:
No Javadoc available
Method code:
public void testRemoveTrack() {
getWorld().set(ITEM.GAME_RULES, GameRules.NO_RESTRICTIONS);
TrackRule trackRule = (TrackRule) getWorld().get(SKEY.TRACK_RULES, 0);
assertBuildTrackSucceeds(new ImPoint(0, 5), east, trackRule);
assertBuildTrackSucceeds(new ImPoint(0, 6), east, trackRule);
assertBuildTrackSucceeds(new ImPoint(1, 6), east, trackRule);
assertBuildTrackSucceeds(new ImPoint(0, 7), east, trackRule);
assertBuildTrackSucceeds(new ImPoint(1, 7), east, trackRule);
assertBuildTrackSucceeds(new ImPoint(2, 7), east, trackRule);
// Remove only track piece built.
assertRemoveTrackSucceeds(new ImPoint(0, 5), east);
TrackConfiguration trackConfiguration = ((FreerailsTile) getWorld().getTile(0, 5))
.getTrackPiece().getTrackConfiguration();
TrackConfiguration expected = NullTrackPiece.getInstance().getTrackConfiguration();
assertEquals(expected,
trackConfiguration);
TrackConfiguration trackConfiguration2 = ((FreerailsTile) getWorld().getTile(1, 5))
.getTrackPiece().getTrackConfiguration();
assertEquals(expected,
trackConfiguration2);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMove.canConnect2OtherRRsTrack
Javadoc:
No Javadoc available
Method code:
protected static boolean canConnect2OtherRRsTrack(ReadOnlyWorld world) {
GameRules rules = (GameRules) world.get(ITEM.GAME_RULES);
return rules.isCanConnect2OtherRRTrack();
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMove.check4overlap
Javadoc:
/** * This method may be called under 3 possible conditions: (1) when a station * is getting built, (2) when a station is getting upgraded, (3) when a * station is getting removed. */
Method code:
/**
* This method may be called under 3 possible conditions: (1) when a station
* is getting built, (2) when a station is getting upgraded, (3) when a
* station is getting removed.
*/
protected static MoveStatus check4overlap(World w, ImPoint location,
TrackPiece trackPiece) {
/*
* Fix for 915945 (Stations should not overlap) Check that there is not
* another station whose radius overlaps with the one we are building.
*/
TrackRule thisStationType = trackPiece.getTrackRule();
assert thisStationType.isStation();
for (int player = 0; player < w.getNumberOfPlayers(); player++) {
FreerailsPrincipal principal = w.getPlayer(player).getPrincipal();
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
while (wi.next()) {
StationModel station = (StationModel) wi.getElement();
/*
* Fix for bug 948675 - Can't upgrade station types If locations
* are the same, then we are upgrading a station so it doesn't
* matter if the radii overlap.
*/
if (location.x == station.x && location.y == station.y) {
continue;
}
FreerailsTile tile = (FreerailsTile) w.getTile(station.x,
station.y);
TrackRule otherStationType = tile.getTrackPiece().getTrackRule();
assert otherStationType.isStation();
int sumOfRadii = otherStationType.getStationRadius()
+ thisStationType.getStationRadius();
int sumOfRadiiSquared = sumOfRadii * sumOfRadii;
int xDistance = station.x - location.x;
int yDistance = station.y - location.y;
// Do radii overlap?
boolean xOverlap = sumOfRadiiSquared >= (xDistance * xDistance);
boolean yOverlap = sumOfRadiiSquared >= (yDistance * yDistance);
if (xOverlap && yOverlap) {
String message = "Too close to " + station.getStationName();
return MoveStatus.moveFailed(message);
}
}
}
return MoveStatus.MOVE_OK;
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMove.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus moveStatus = tryDoMove(w, p);
if (!moveStatus.isOk()) {
return moveStatus;
}
move(w, this.trackPieceBefore, this.trackPieceAfter);
return moveStatus;
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMove.getLocation
Javadoc:
No Javadoc available
Method code:
public ImPoint getLocation() {
return location;
}
No outgoing methods.
jfreerails.move.ChangeTrackPieceMove.getNewTrackPiece
Javadoc:
No Javadoc available
Method code:
public TrackPiece getNewTrackPiece() {
return trackPieceAfter;
}
No outgoing methods.
jfreerails.move.ChangeTrackPieceMove.getOldTrackPiece
Javadoc:
No Javadoc available
Method code:
public TrackPiece getOldTrackPiece() {
return trackPieceBefore;
}
No outgoing methods.
jfreerails.move.ChangeTrackPieceMove.getUpdatedTiles
Javadoc:
No Javadoc available
Method code:
public Rectangle getUpdatedTiles() {
// If we are building or removing a station,
// we need to repaint/remove the station radius
// that appears on the map.
int radius = 1;
TrackRule trackRuleAfter = this.trackPieceAfter.getTrackRule();
if (trackRuleAfter.isStation()) {
radius = Math.max(radius, trackRuleAfter.getStationRadius());
}
TrackRule trackRuleBefore = this.trackPieceBefore.getTrackRule();
if (trackRuleBefore.isStation()) {
radius = Math.max(radius, trackRuleBefore.getStationRadius());
}
// Just to be safe.
radius++;
int x;
int y;
int width;
int height;
x = location.x - radius;
y = location.y - radius;
width = radius * 2 + 1;
height = radius * 2 + 1;
return new Rectangle(x, y, width, height);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMove.move
Javadoc:
No Javadoc available
Method code:
private void move(World w, TrackPiece oldTrackPiece,
TrackPiece newTrackPiece) {
// FIXME why is oldTrackPiece not used???
FreerailsTile oldTile = (FreerailsTile) w.getTile(location.x,
location.y);
int terrain = oldTile.getTerrainTypeID();
FreerailsTile newTile = FreerailsTile.getInstance(terrain,
newTrackPiece);
w.setTile(location.x, location.y, newTile);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMove.noDiagonalTrackConflicts
Javadoc:
No Javadoc available
Method code:
private boolean noDiagonalTrackConflicts(ImPoint point, int trackTemplate,
World w) {
/*
* This method is needs replacing. It only deals with flat track pieces,
* and is rather hard to make sense of. LL
*/
// int trackTemplate = (1 << (3 * (1 + tv.getY()) + (1 + tv.getX())));
int trackTemplateAbove;
int trackTemplateBelow;
int cornersTemplate = TrackConfiguration
.stringTemplate2Int("101000101");
trackTemplate = trackTemplate & cornersTemplate;
Dimension mapSize = new Dimension(w.getMapWidth(), w.getMapHeight());
// Avoid array-out-of-bounds exceptions.
if (point.y > 0) {
FreerailsTile ft = (FreerailsTile)w.getTile(point.x, point.y - 1);
TrackPiece tp = ft.getTrackPiece();
trackTemplateAbove = tp.getTrackGraphicID();
} else {
trackTemplateAbove = 0;
}
if ((point.y + 1) < mapSize.height) {
FreerailsTile ft = (FreerailsTile)w.getTile(point.x, point.y + 1);
TrackPiece tp = ft.getTrackPiece();
trackTemplateBelow = tp.getTrackGraphicID();
} else {
trackTemplateBelow = 0;
}
trackTemplateAbove = trackTemplateAbove >> 6;
trackTemplateBelow = trackTemplateBelow << 6;
trackTemplate = trackTemplate
& (trackTemplateAbove | trackTemplateBelow);
if (trackTemplate != 0) {
return false;
// There is a clash.
}
return true;
// Things are ok.
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMove.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
return tryMove(w, this.trackPieceBefore, this.trackPieceAfter);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMove.tryMove
Javadoc:
No Javadoc available
Method code:
private MoveStatus tryMove(World w, TrackPiece oldTrackPiece,
TrackPiece newTrackPiece) {
// Check that location is on the map.
if (!w.boundsContain(location.x, location.y)) {
return MoveStatus
.moveFailed("Tried to build track outside the map.");
}
// Check that we are not changing another players track if this is not
// allowed.
if (!canConnect2OtherRRsTrack(w)) {
// If either the new or old track piece is null, we are ok.
int oldRuleNumber = oldTrackPiece.getTrackTypeID();
int newRuleNumber = newTrackPiece.getTrackTypeID();
if (NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER != oldRuleNumber
&& NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER != newRuleNumber) {
int oldOwner = oldTrackPiece.getOwnerID();
int newOwner = newTrackPiece.getOwnerID();
if (oldOwner != newOwner) {
return MoveStatus
.moveFailed("Not allowed to connect to other RR");
}
}
}
// Check that the current track piece at this.location is
// the same as this.oldTrackPiece.
TrackPiece currentTrackPieceAtLocation = ((FreerailsTile) w.getTile(
location.x, location.y)).getTrackPiece();
TrackRule expectedTrackRule = oldTrackPiece.getTrackRule();
TrackRule actualTrackRule = currentTrackPieceAtLocation.getTrackRule();
if (!expectedTrackRule.equals(actualTrackRule)) {
return MoveStatus.moveFailed("Expected '"
+ expectedTrackRule.getTypeName() + "' but found '"
+ actualTrackRule.getTypeName() + "' at " + location.x
+ " ," + location.y);
}
if (currentTrackPieceAtLocation.getTrackConfiguration() != oldTrackPiece
.getTrackConfiguration()) {
return MoveStatus
.moveFailed("Unexpected track piece found at location: "
+ location.x + " ," + location.y);
}
// Check that oldTrackPiece is not the same as newTrackPiece
if ((oldTrackPiece.getTrackConfiguration() == newTrackPiece
.getTrackConfiguration())
&& (oldTrackPiece.getTrackRule() == newTrackPiece
.getTrackRule())) {
return MoveStatus.moveFailed("Already track here!");
}
// Check for illegal track configurations.
if (!(oldTrackPiece.getTrackRule().trackPieceIsLegal(
oldTrackPiece.getTrackConfiguration()) && newTrackPiece
.getTrackRule().trackPieceIsLegal(
newTrackPiece.getTrackConfiguration()))) {
return MoveStatus.moveFailed("Illegal track configuration.");
}
// Check for diagonal conflicts.
if (!(noDiagonalTrackConflicts(location, oldTrackPiece
.getTrackGraphicID(), w) && noDiagonalTrackConflicts(location,
newTrackPiece.getTrackGraphicID(), w))) {
return MoveStatus
.moveFailed("Illegal track configuration - diagonal conflict");
}
int terrainType = ((FreerailsTile) w.getTile(location.x, location.y))
.getTerrainTypeID();
TerrainType tt = (TerrainType) w.get(SKEY.TERRAIN_TYPES, terrainType);
if (!newTrackPiece.getTrackRule().canBuildOnThisTerrainType(
tt.getCategory())) {
String thisTrackType = newTrackPiece.getTrackRule().getTypeName();
String terrainCategory = tt.getCategory().toString().toLowerCase();
return MoveStatus.moveFailed("Can't build " + thisTrackType
+ " on " + terrainCategory);
}
// Check 4 overlapping stations.
if (newTrackPiece.getTrackRule().isStation()) {
MoveStatus ms = ChangeTrackPieceMove.check4overlap(w, location,
newTrackPiece);
if (!ms.ok)
return ms;
}
return MoveStatus.MOVE_OK;
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMove.tryUndoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
return tryMove(w, this.trackPieceAfter, this.trackPieceBefore);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMove.undoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus moveStatus = tryUndoMove(w, p);
if (!moveStatus.isOk()) {
return moveStatus;
}
move(w, this.trackPieceAfter, this.trackPieceBefore);
return moveStatus;
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMoveTest.assertMoveDoMoveIsOk
Javadoc:
No Javadoc available
Method code:
protected void assertMoveDoMoveIsOk(TrackPiece oldTrackPiece,
TrackPiece newTrackPiece) {
TrackMove move;
MoveStatus moveStatus;
move = new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece,
new ImPoint(0, 0));
moveStatus = move.doMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(moveStatus);
assertEquals(true, moveStatus.isOk());
TrackConfiguration actual = ((FreerailsTile)getWorld().getTile(0, 0)).getTrackPiece().getTrackConfiguration();
assertEquals(newTrackPiece.getTrackConfiguration(),
actual);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMoveTest.main
Javadoc:
No Javadoc available
Method code:
public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMoveTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() {
setHasSetupBeenCalled(true);
setWorld(new WorldImpl(20, 20));
getWorld().set(ITEM.GAME_RULES, GameRules.NO_RESTRICTIONS);
MapFixtureFactory.generateTrackRuleList(getWorld());
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMoveTest.suite
Javadoc:
No Javadoc available
Method code:
public static junit.framework.Test suite() {
junit.framework.TestSuite testSuite = new junit.framework.TestSuite(
ChangeTrackPieceMoveTest.class);
return testSuite;
}
No outgoing methods.
jfreerails.move.ChangeTrackPieceMoveTest.testDoMove
Javadoc:
No Javadoc available
Method code:
public void testDoMove() {
setUp();
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
TrackConfiguration newConfig;
// Try building the simplest piece of track.
newConfig = TrackConfiguration.getFlatInstance("000010000");
oldTrackPiece = ((FreerailsTile) getWorld().getTile(0, 0)).getTrackPiece();
TrackRule r = (TrackRule) getWorld().get(SKEY.TRACK_RULES, 0);
newTrackPiece = new TrackPieceImpl(newConfig, r, 0, 0);
assertMoveDoMoveIsOk(oldTrackPiece, newTrackPiece);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMoveTest.testMove
Javadoc:
No Javadoc available
Method code:
@Override
public void testMove() {
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
TrackConfiguration newConfig;
newConfig = TrackConfiguration.getFlatInstance("000010000");
oldTrackPiece = ((FreerailsTile) getWorld().getTile(0, 0)).getTrackPiece();
TrackRule r = (TrackRule) getWorld().get(SKEY.TRACK_RULES, 0);
newTrackPiece = new TrackPieceImpl(newConfig, r, 0, 0);
Move move = new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece,
new ImPoint(0, 0));
assertSurvivesSerialisation(move);
assertOkButNotRepeatable(move);
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMoveTest.testTryDoMove
Javadoc:
No Javadoc available
Method code:
public void testTryDoMove() {
setUp();
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
TrackConfiguration newConfig;
TrackMove move;
MoveStatus moveStatus;
// Try building the simplest piece of track.
newConfig = TrackConfiguration.getFlatInstance("000010000");
oldTrackPiece = ((FreerailsTile) getWorld().getTile(0, 0)).getTrackPiece();
final int trackRuleID = 0;
final TrackRule r = (TrackRule) getWorld().get(SKEY.TRACK_RULES,
trackRuleID);
newTrackPiece = new TrackPieceImpl(newConfig, r, 0, trackRuleID);
move = new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece,
new ImPoint(0, 0));
moveStatus = move.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(moveStatus);
assertEquals(true, moveStatus.isOk());
// As above but with newTrackPiece and oldTrackPiece in the wrong order,
// should fail.
move = new ChangeTrackPieceMove(newTrackPiece, oldTrackPiece,
new ImPoint(0, 0));
moveStatus = move.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(moveStatus);
assertEquals(false, moveStatus.isOk());
// Try a move that does nothing, i.e. oldTrackPiece==newTrackPiece,
// should fail.
move = new ChangeTrackPieceMove(oldTrackPiece, oldTrackPiece,
new ImPoint(0, 0));
moveStatus = move.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(moveStatus);
assertEquals(false, moveStatus.isOk());
// Try buildingtrack outside the map.
move = new ChangeTrackPieceMove(newTrackPiece, oldTrackPiece,
new ImPoint(100, 0));
moveStatus = move.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(moveStatus);
assertEquals(false, moveStatus.isOk());
// Try building an illegal track configuration.
newConfig = TrackConfiguration.getFlatInstance("000011111");
newTrackPiece = new TrackPieceImpl(newConfig, r, 0, trackRuleID);
move = new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece,
new ImPoint(0, 0));
moveStatus = move.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertEquals(false, moveStatus.isOk());
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrackPieceMoveTest.testTryUndoMove
Javadoc:
No Javadoc available
Method code:
public void testTryUndoMove() {
setUp();
}
Outgoing Methods (calls):
jfreerails.move.ChangeTrainMove.generateMove
Javadoc:
No Javadoc available
Method code:
public static ChangeTrainMove generateMove(int id, TrainModel before,
int newEngine, ImInts newWagons, FreerailsPrincipal p) {
TrainModel after = before.getNewInstance(newEngine, newWagons);
return new ChangeTrainMove(id, before, after, p);
}
Outgoing Methods (calls):
jfreerails.move.CompositeMove.compositeTest
Javadoc:
/** * Subclasses may override this method to perform tests which pass or fail * depending on the combination of moves making up this composite move. */
Method code:
/**
* Subclasses may override this method to perform tests which pass or fail
* depending on the combination of moves making up this composite move.
*/
MoveStatus compositeTest(World w, FreerailsPrincipal p) {
return MoveStatus.MOVE_OK;
}
No outgoing methods.
jfreerails.move.CompositeMove.doMove
Javadoc:
No Javadoc available
Method code:
public final MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = compositeTest(w, p);
if (!ms.ok) {
return ms;
}
for (int i = 0; i < moves.size(); i++) {
ms = moves.get(i).doMove(w, p);
if (!ms.ok) {
// Undo any moves we have already done.
undoMoves(w, i - 1, p);
return ms;
}
}
return ms;
}
Outgoing Methods (calls):
jfreerails.move.CompositeMove.getMove
Javadoc:
/** * This method lets sub classes look at the moves. */
Method code:
/**
* This method lets sub classes look at the moves.
*/
final Move getMove(int i) {
return moves.get(i);
}
Outgoing Methods (calls):
jfreerails.move.CompositeMove.getMoves
Javadoc:
No Javadoc available
Method code:
public final ImList<Move> getMoves() {
return moves;
}
No outgoing methods.
jfreerails.move.CompositeMove.redoMoves
Javadoc:
No Javadoc available
Method code:
private void redoMoves(World w, int number, FreerailsPrincipal p) {
for (int i = number; i < moves.size(); i++) {
MoveStatus ms = moves.get(i).doMove(w, p);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
}
}
Outgoing Methods (calls):
jfreerails.move.CompositeMove.size
Javadoc:
No Javadoc available
Method code:
public int size(){
return moves.size();
}
Outgoing Methods (calls):
jfreerails.move.CompositeMove.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
// Since whether a move later in the list goes through could
// depend on whether an earlier move has been executed, we need
// actually execute moves, then undo them to test whether the
// array of moves can be executed ok.
MoveStatus ms = doMove(w, p);
if (ms.ok) {
// We just wanted to see if we could do them so we undo them again.
undoMoves(w, moves.size() - 1, p);
}
// If its not ok, then doMove would have undone the moves so we don't
// need to undo them.
return ms;
}
Outgoing Methods (calls):
jfreerails.move.CompositeMove.tryUndoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = undoMove(w, p);
if (ms.isOk()) {
redoMoves(w, 0, p);
}
return ms;
}
Outgoing Methods (calls):
jfreerails.move.CompositeMove.undoMove
Javadoc:
No Javadoc available
Method code:
public final MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = MoveStatus.MOVE_OK;
for (int i = moves.size() - 1; i >= 0; i--) {
ms = moves.get(i).undoMove(w, p);
if (!ms.ok) {
// Redo any moves we have already undone.
redoMoves(w, i + 1, p);
return ms;
}
}
return ms;
}
Outgoing Methods (calls):
jfreerails.move.CompositeMove.undoMoves
Javadoc:
No Javadoc available
Method code:
private void undoMoves(World w, int number, FreerailsPrincipal p) {
for (int i = number; i >= 0; i--) {
MoveStatus ms = moves.get(i).undoMove(w, p);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
}
}
Outgoing Methods (calls):
jfreerails.move.CompositeMoveTest.testMove
Javadoc:
No Javadoc available
Method code:
@Override
public void testMove() {
Move[] moves = new Move[4];
moves[0] = new AddItemToListMove(KEY.STATIONS, 0, station1,
MapFixtureFactory.TEST_PRINCIPAL);
moves[1] = new AddItemToListMove(KEY.STATIONS, 1, station2,
MapFixtureFactory.TEST_PRINCIPAL);
moves[2] = new AddItemToListMove(KEY.STATIONS, 2, station3,
MapFixtureFactory.TEST_PRINCIPAL);
moves[3] = new AddItemToListMove(KEY.STATIONS, 3, station4,
MapFixtureFactory.TEST_PRINCIPAL);
Move compositeMove = new CompositeMove(moves);
assertSurvivesSerialisation(compositeMove);
assertTryMoveIsOk(compositeMove);
assertEquals("The stations should not have been add yet.", 0,
getWorld().size(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS));
assertDoMoveIsOk(compositeMove);
assertEquals("The stations should have been add now.", 4, getWorld()
.size(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS));
assertTryUndoMoveIsOk(compositeMove);
assertUndoMoveIsOk(compositeMove);
assertOkButNotRepeatable(compositeMove);
}
Outgoing Methods (calls):
jfreerails.move.ListMove.getAfter
Javadoc:
/** * @return the new item or null if not any. */
Method code:
/**
* @return the new item or null if not any.
*/
FreerailsSerializable getAfter();
No outgoing methods.
jfreerails.move.ListMove.getBefore
Javadoc:
/** * @return the old item or null if not any. */
Method code:
/**
* @return the old item or null if not any.
*/
FreerailsSerializable getBefore();
No outgoing methods.
jfreerails.move.ListMove.getIndex
Javadoc:
/** * @return the index of the item which changed. */
Method code:
/**
* @return the index of the item which changed.
*/
int getIndex();
No outgoing methods.
jfreerails.move.ListMove.getKey
Javadoc:
/** * @return the type of object which was changed */
Method code:
/**
* @return the type of object which was changed
*/
KEY getKey();
No outgoing methods.
jfreerails.move.ListMove.getPrincipal
Javadoc:
No Javadoc available
Method code:
FreerailsPrincipal getPrincipal();
No outgoing methods.
jfreerails.move.MapDiffMoveTest.testMove
Javadoc:
No Javadoc available
Method code:
@Override
public void testMove() {
World world2 = this.getWorld();
WorldDiffs worldDiff = new WorldDiffs(world2);
FreerailsTile tile = (FreerailsTile) world2.getTile(2, 2);
assertNotNull(tile);
assertEquals(tile, worldDiff.getTile(2, 2));
FreerailsTile newTile = FreerailsTile.getInstance(999);
worldDiff.setTile(3, 5, newTile);
assertEquals(newTile, worldDiff.getTile(3, 5));
Move m = new WorldDiffMove(world2, worldDiff, WorldDiffMove.Cause.Other);
this.assertDoMoveIsOk(m);
this.assertUndoMoveIsOk(m);
this.assertDoThenUndoLeavesWorldUnchanged(m);
this.assertSurvivesSerialisation(m);
}
Outgoing Methods (calls):
jfreerails.move.MapUpdateMove.getUpdatedTiles
Javadoc:
No Javadoc available
Method code:
Rectangle getUpdatedTiles();
No outgoing methods.
jfreerails.move.Move.doMove
Javadoc:
/** * Executes this move on the specified world object. */
Method code:
/**
* Executes this move on the specified world object.
*/
MoveStatus doMove(World w, FreerailsPrincipal p);
No outgoing methods.
jfreerails.move.Move.tryDoMove
Javadoc:
/** * Tests whether this Move can be executed on the specified world object, * this method should leave the world object unchanged. */
Method code:
/**
* Tests whether this Move can be executed on the specified world object,
* this method should leave the world object unchanged.
*/
MoveStatus tryDoMove(World w, FreerailsPrincipal p);
No outgoing methods.
jfreerails.move.Move.tryUndoMove
Javadoc:
/** * Tests whether this Move can be undone on the specified world object, this * method should leave the world object unchanged. */
Method code:
/**
* Tests whether this Move can be undone on the specified world object, this
* method should leave the world object unchanged.
*/
MoveStatus tryUndoMove(World w, FreerailsPrincipal p);
No outgoing methods.
jfreerails.move.Move.undoMove
Javadoc:
/** * If <code>doMove</code> has just been executed on the specified world * object, calling this method changes the state of the world object back to * how it was before <code>doMove</code> was called. */
Method code:
/**
* If <code>doMove</code> has just been executed on the specified world
* object, calling this method changes the state of the world object back to
* how it was before <code>doMove</code> was called.
*/
MoveStatus undoMove(World w, FreerailsPrincipal p);
No outgoing methods.
jfreerails.move.MoveStatus.isOk
Javadoc:
No Javadoc available
Method code:
public boolean isOk() {
return ok;
}
No outgoing methods.
jfreerails.move.MoveStatus.moveFailed
Javadoc:
No Javadoc available
Method code:
public static MoveStatus moveFailed(String reason) {
return new MoveStatus(false, reason);
}
No outgoing methods.
jfreerails.move.MoveStatus.printStackTrack
Javadoc:
No Javadoc available
Method code:
public void printStackTrack(){
if(null != t)
t.printStackTrace();
}
No outgoing methods.
jfreerails.move.MoveStatus.readResolve
Javadoc:
/** * Avoid creating a duplicate when deserializing. */
Method code:
/**
* Avoid creating a duplicate when deserializing.
*/
private Object readResolve() {
if (ok) {
return MOVE_OK;
}
return this;
}
No outgoing methods.
jfreerails.move.NextActivityMove.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.ok)
w.add(principal, index, activity);
return ms;
}
Outgoing Methods (calls):
jfreerails.move.NextActivityMove.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
// Check that active entity exists.
if (w.size(principal) <= index)
return MoveStatus.moveFailed("Index out of range. "+w.size(principal)+"<= "+index);
return MoveStatus.MOVE_OK;
}
Outgoing Methods (calls):
jfreerails.move.NextActivityMove.tryUndoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
ActivityIterator ai = w.getActivities(principal, index);
ai.gotoLastActivity();
Activity act = ai.getActivity();
if (act.equals(activity))
return MoveStatus.MOVE_OK;
return MoveStatus.moveFailed("Expected " + activity + " but found "
+ act);
}
Outgoing Methods (calls):
jfreerails.move.NextActivityMove.undoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.ok)
w.removeLastActivity(principal, index);
return ms;
}
Outgoing Methods (calls):
jfreerails.move.NextActivityMoveTest.testMove
Javadoc:
No Javadoc available
Method code:
@Override
public void testMove() {
World w = getWorld();
FreerailsPrincipal principal = getPrincipal();
Activity act = new WorldImplTest.TestActivity(50);
w.addActiveEntity(principal, act);
Activity act2 = new WorldImplTest.TestActivity(60);
Move move = new NextActivityMove(act2, 0,
principal);
assertSurvivesSerialisation(move);
assertOkAndRepeatable(move);
}
Outgoing Methods (calls):
jfreerails.move.NextActivityMoveTest.testMove2
Javadoc:
No Javadoc available
Method code:
public void testMove2() {
World w = getWorld();
FreerailsPrincipal principal = getPrincipal();
Activity act = new WorldImplTest.TestActivity(50);
w.addActiveEntity(principal, act);
Activity act2 = new WorldImplTest.TestActivity(60);
Move move = new NextActivityMove(act2, 0,
principal);
assertDoThenUndoLeavesWorldUnchanged(move);
}
Outgoing Methods (calls):
jfreerails.move.NextActivityMoveTest.testStackingOfActivities
Javadoc:
No Javadoc available
Method code:
public void testStackingOfActivities() {
World w = getWorld();
FreerailsPrincipal principal = getPrincipal();
Activity act = new WorldImplTest.TestActivity(50);
w.addActiveEntity(principal, act);
Activity act2 = new WorldImplTest.TestActivity(60);
Move move = new NextActivityMove(act2, 0,
principal);
assertDoMoveIsOk(move);
GameTime currentTime = new GameTime(0);
assertEquals(currentTime, w.currentTime());
ActivityIterator it = w.getActivities(principal, 0);
assertEquals(it.getActivity(), act);
assertEquals(it.getStartTime(), currentTime.getTicks(), 0.00001);
assertEquals(50d, it.getDuration(), 0.00001);
assertEquals(50d, it.getFinishTime(), 0.00001);
assertTrue(it.hasNext());
it.nextActivity();
assertEquals(it.getActivity(), act2);
assertEquals(50, it.getStartTime(), 0.00001);
assertEquals(60, it.getDuration(), 0.0001d);
assertEquals(110, it.getFinishTime(), 0.00001);
}
Outgoing Methods (calls):
jfreerails.move.RemoveCargoBundleMoveTest.testMove
Javadoc:
No Javadoc available
Method code:
@Override
public void testMove() {
MutableCargoBundle bundleA;
MutableCargoBundle bundleB;
bundleA = new MutableCargoBundle();
bundleB = new MutableCargoBundle();
bundleA.setAmount(new CargoBatch(1, 2, 3, 4, 0), 5);
bundleB.setAmount(new CargoBatch(1, 2, 3, 4, 0), 5);
assertEquals(bundleA, bundleB);
Move m = new RemoveCargoBundleMove(0, bundleB.toImmutableCargoBundle(),
MapFixtureFactory.TEST_PRINCIPAL);
assertSurvivesSerialisation(m);
assertTryMoveFails(m);
assertTryUndoMoveFails(m);
getWorld().add(MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES,
bundleA.toImmutableCargoBundle());
assertTryMoveIsOk(m);
assertOkButNotRepeatable(m);
}
Outgoing Methods (calls):
jfreerails.move.RemoveItemFromListMove.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.isOk()) {
w.set(principal, listKey, index, null);
}
return ms;
}
Outgoing Methods (calls):
jfreerails.move.RemoveItemFromListMove.getAfter
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable getAfter() {
return null;
}
No outgoing methods.
jfreerails.move.RemoveItemFromListMove.getBefore
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable getBefore() {
return item;
}
No outgoing methods.
jfreerails.move.RemoveItemFromListMove.getIndex
Javadoc:
No Javadoc available
Method code:
public int getIndex() {
return index;
}
No outgoing methods.
jfreerails.move.RemoveItemFromListMove.getKey
Javadoc:
No Javadoc available
Method code:
public KEY getKey() {
return listKey;
}
No outgoing methods.
jfreerails.move.RemoveItemFromListMove.getPrincipal
Javadoc:
No Javadoc available
Method code:
public FreerailsPrincipal getPrincipal() {
return principal;
}
No outgoing methods.
jfreerails.move.RemoveItemFromListMove.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.size(principal, listKey) < (index + 1)) {
return MoveStatus.moveFailed("w.size(listKey)="
+ w.size(principal, listKey) + " but index =" + index);
}
FreerailsSerializable item2remove = w.get(principal, listKey, index);
if (null == item2remove) {
return MoveStatus.moveFailed("The item at position " + index
+ " has already been removed.");
}
if (!item.equals(item2remove)) {
String reason = "The item at position " + index + " in the list ("
+ item2remove.toString() + ") is not the expected item ("
+ item.toString() + ").";
return MoveStatus.moveFailed(reason);
}
return MoveStatus.MOVE_OK;
}
Outgoing Methods (calls):
jfreerails.move.RemoveItemFromListMove.tryUndoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
if (w.size(principal, listKey) < (index + 1)) {
return MoveStatus.moveFailed("w.size(listKey)="
+ w.size(principal, listKey) + " but index =" + index);
}
if (null != w.get(principal, listKey, index)) {
String reason = "The item at position " + index + " in the list ("
+ w.get(principal, listKey, index).toString()
+ ") is not the expected item (null).";
return MoveStatus.moveFailed(reason);
}
return MoveStatus.MOVE_OK;
}
Outgoing Methods (calls):
jfreerails.move.RemoveItemFromListMove.undoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.isOk()) {
w.set(principal, listKey, index, this.item);
}
return ms;
}
Outgoing Methods (calls):
jfreerails.move.RemoveStationMove.getInstance
Javadoc:
No Javadoc available
Method code:
static RemoveStationMove getInstance(ReadOnlyWorld w,
ChangeTrackPieceMove removeTrackMove, FreerailsPrincipal principal) {
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
int stationIndex = -1;
while (wi.next()) {
StationModel station = (StationModel) wi.getElement();
if (station.x == removeTrackMove.getLocation().x
&& station.y == removeTrackMove.getLocation().y) {
// We have found the station!
stationIndex = wi.getIndex();
break;
}
}
if (-1 == stationIndex) {
throw new IllegalArgumentException("Could find a station at "
+ removeTrackMove.getLocation().x + ", "
+ removeTrackMove.getLocation().y);
}
StationModel station2remove = (StationModel) w.get(principal,
KEY.STATIONS, stationIndex);
ArrayList<Move> moves = new ArrayList<Move>();
moves.add(removeTrackMove);
moves.add(new RemoveItemFromListMove(KEY.STATIONS, stationIndex,
station2remove, principal));
// Now update any train schedules that include this station.
WorldIterator schedules = new NonNullElements(KEY.TRAIN_SCHEDULES, w,
principal);
while (schedules.next()) {
ImmutableSchedule schedule = (ImmutableSchedule) schedules
.getElement();
if (schedule.stopsAtStation(stationIndex)) {
MutableSchedule mutableSchedule = new MutableSchedule(schedule);
mutableSchedule.removeAllStopsAtStation(stationIndex);
Move changeScheduleMove = new ChangeTrainScheduleMove(schedules
.getIndex(), schedule, mutableSchedule
.toImmutableSchedule(), principal);
moves.add(changeScheduleMove);
}
}
return new RemoveStationMove(moves);
}
Outgoing Methods (calls):
jfreerails.move.RemoveStationMove.getUpdatedTiles
Javadoc:
No Javadoc available
Method code:
public Rectangle getUpdatedTiles() {
TrackMove tm = (TrackMove) getMove(0);
return tm.getUpdatedTiles();
}
Outgoing Methods (calls):
jfreerails.move.RemoveTrainMove.getInstance
Javadoc:
No Javadoc available
Method code:
public static RemoveTrainMove getInstance(int index, FreerailsPrincipal p,
ReadOnlyWorld world) {
TrainModel train = (TrainModel) world.get(p, KEY.TRAINS, index);
int scheduleId = train.getScheduleID();
ImmutableSchedule schedule = (ImmutableSchedule) world.get(
p, KEY.TRAIN_SCHEDULES, scheduleId);
int cargoBundleId = train.getCargoBundleID();
ImmutableCargoBundle cargoBundle = (ImmutableCargoBundle) world.get(
p, KEY.CARGO_BUNDLES, cargoBundleId);
// TrainPositionOnMap position =
// (TrainPositionOnMap)world.get(KEY.TRAIN_POSITIONS, index, p);
Move removeTrain = new RemoveItemFromListMove(KEY.TRAINS, index, train,
p);
Move removeCargobundle = new RemoveItemFromListMove(KEY.CARGO_BUNDLES,
cargoBundleId, cargoBundle, p);
Move removeSchedule = new RemoveItemFromListMove(KEY.TRAIN_SCHEDULES,
scheduleId, schedule, p);
// Move removePosition = new RemoveItemFromListMove(KEY.TRAIN_POSITIONS,
// index, position, p);
return new RemoveTrainMove(new Move[] { removeTrain, removeCargobundle,
removeSchedule /* , removePosition */
});
}
Outgoing Methods (calls):
jfreerails.move.TimeTickMove.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryDoMove(w, p);
if (status.ok) {
w.setTime(newTime);
}
return status;
}
Outgoing Methods (calls):
jfreerails.move.TimeTickMove.getMove
Javadoc:
No Javadoc available
Method code:
public static TimeTickMove getMove(ReadOnlyWorld w) {
GameTime oldTime = w.currentTime();
GameTime newTime = new GameTime(oldTime.getTicks() + 1);
return new TimeTickMove(oldTime, newTime);
}
Outgoing Methods (calls):
jfreerails.move.TimeTickMove.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.currentTime().equals(oldTime)) {
return MoveStatus.MOVE_OK;
}
String string = "oldTime = " + oldTime.getTicks() + " <=> "
+ "currentTime " + (w.currentTime()).getTicks();
return MoveStatus.moveFailed(string);
}
Outgoing Methods (calls):
jfreerails.move.TimeTickMove.tryUndoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
GameTime time = w.currentTime();
if (time.equals(newTime)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + newTime + ", found " + time);
}
Outgoing Methods (calls):
jfreerails.move.TimeTickMove.undoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryUndoMove(w, p);
if (status.isOk()) {
w.setTime(oldTime);
}
return status;
}
Outgoing Methods (calls):
jfreerails.move.TrackMoveTransactionsGenerator.addTransactions
Javadoc:
No Javadoc available
Method code:
public CompositeMove addTransactions(Move move) {
int numberOfTrackTypes = w.size(SKEY.TRACK_RULES);
trackAdded = new int[numberOfTrackTypes];
trackRemoved = new int[numberOfTrackTypes];
fixedCostsStations = 0;
fixedCostsBridges = 0;
unpackMove(move);
generateTransactions();
int numberOfMoves = 1 + transactions.size();
Move[] moves = new Move[numberOfMoves];
moves[0] = move;
for (int i = 0; i < transactions.size(); i++) {
Transaction t = transactions.get(i);
moves[i + 1] = new AddTransactionMove(principal, t, true);
}
return new CompositeMove(moves);
}
Outgoing Methods (calls):
jfreerails.move.TrackMoveTransactionsGenerator.generateTransactions
Javadoc:
No Javadoc available
Method code:
private void generateTransactions() {
transactions.clear();
// For each track type, generate a transaction if any pieces of the type
// have been added or removed.
for (int i = 0; i < trackAdded.length; i++) {
int numberAdded = trackAdded[i];
if (0 != numberAdded) {
TrackRule rule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
Money m = rule.getPrice();
Money total = new Money(-m.getAmount() * numberAdded
/ TrackConfiguration.LENGTH_OF_STRAIGHT_TRACK_PIECE);
Transaction t = new AddItemTransaction(TRACK, i, numberAdded,
total);
transactions.add(t);
}
int numberRemoved = trackRemoved[i];
if (0 != numberRemoved) {
TrackRule rule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
Money m = rule.getPrice();
Money total = new Money((m.getAmount() * numberRemoved)
/ TrackConfiguration.LENGTH_OF_STRAIGHT_TRACK_PIECE);
// You only get half the money back.
total = new Money(total.getAmount() / 2);
Transaction t = new AddItemTransaction(TRACK, i,
-numberRemoved, total);
transactions.add(t);
}
}
if (0 != fixedCostsStations) {
Transaction t = new AddItemTransaction(STATIONS, -1, -1, new Money(
fixedCostsStations));
transactions.add(t);
}
if (0 != fixedCostsBridges) {
Transaction t = new AddItemTransaction(BRIDGES, -1, -1, new Money(
fixedCostsBridges));
transactions.add(t);
}
}
Outgoing Methods (calls):
jfreerails.move.TrackMoveTransactionsGenerator.processMove
Javadoc:
No Javadoc available
Method code:
private void processMove(ChangeTrackPieceMove move) {
TrackPiece newTrackPiece = move.getNewTrackPiece();
TrackRule newTrackRule = newTrackPiece.getTrackRule();
final int ruleAfter = newTrackPiece.getTrackTypeID();
TrackPiece oldTrackPiece = move.getOldTrackPiece();
final int ruleBefore = oldTrackPiece.getTrackTypeID();
final int oldLength = oldTrackPiece.getTrackConfiguration().getLength();
final int newLength = newTrackPiece.getTrackConfiguration().getLength();
if (ruleAfter != ruleBefore) {
TrackRule.TrackCategories category = newTrackRule.getCategory();
switch (category) {
case station: {
fixedCostsStations -= newTrackRule.getFixedCost().getAmount();
break;
}
case bridge: {
fixedCostsBridges -= newTrackRule.getFixedCost().getAmount();
break;
}
default: {
// Do nothing.
}
}
}
if (ruleAfter == ruleBefore) {
if (oldLength < newLength) {
trackAdded[ruleAfter] += (newLength - oldLength);
} else if (oldLength > newLength) {
trackRemoved[ruleAfter] += (oldLength - newLength);
}
return;
}
if (ruleAfter != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
trackAdded[ruleAfter] += newLength;
}
if (ruleBefore != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
trackRemoved[ruleBefore] += oldLength;
}
}
Outgoing Methods (calls):
jfreerails.move.TrackMoveTransactionsGenerator.unpackMove
Javadoc:
No Javadoc available
Method code:
private void unpackMove(Move move) {
if (move instanceof ChangeTrackPieceMove) {
ChangeTrackPieceMove tm = (ChangeTrackPieceMove) move;
processMove(tm);
} else if (move instanceof CompositeMove) {
CompositeMove cm = (CompositeMove) move;
cm.getMoves();
ImList<Move> moves = cm.getMoves();
for (int i = 0; i < moves.size(); i++) {
unpackMove(moves.get(i));
}
}
}
Outgoing Methods (calls):
jfreerails.move.TrackMoveTransactionsGeneratorTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
world = new WorldImpl(20, 20);
MapFixtureFactory.generateTrackRuleList(world);
player = new Player("test player", 0);
world.addPlayer(player);
transactionGenerator = new TrackMoveTransactionsGenerator(world, player
.getPrincipal());
}
Outgoing Methods (calls):
jfreerails.move.TrackMoveTransactionsGeneratorTest.testAddTrackMove
Javadoc:
No Javadoc available
Method code:
public void testAddTrackMove() {
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
TrackConfiguration newConfig;
TrackMove move;
// Try building the simplest piece of track.
newConfig = TrackConfiguration.getFlatInstance("000010000");
oldTrackPiece = ((FreerailsTile) world.getTile(0, 0)).getTrackPiece();
TrackRule r = (TrackRule) world.get(SKEY.TRACK_RULES, 0);
int owner = ChangeTrackPieceCompositeMove.getOwner(
MapFixtureFactory.TEST_PRINCIPAL, world);
newTrackPiece = new TrackPieceImpl(newConfig, r, owner, 0);
move = new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece,
new ImPoint(0, 0));
Move m = transactionGenerator.addTransactions(move);
assertNotNull(m);
}
Outgoing Methods (calls):
jfreerails.move.TrainCrashException.getTrainA
Javadoc:
No Javadoc available
Method code:
public int getTrainA() {
return trainA;
}
No outgoing methods.
jfreerails.move.TrainCrashException.getTrainB
Javadoc:
No Javadoc available
Method code:
public int getTrainB() {
return trainB;
}
No outgoing methods.
jfreerails.move.TransferCargoAtStationMove.generateMove
Javadoc:
No Javadoc available
Method code:
public static TransferCargoAtStationMove generateMove(
ChangeCargoBundleMove changeAtStation,
ChangeCargoBundleMove changeOnTrain, CompositeMove payment,
boolean waiting) {
return new TransferCargoAtStationMove(new Move[] { changeAtStation,
changeOnTrain, payment }, waiting);
}
No outgoing methods.
jfreerails.move.TransferCargoAtStationMove.getChangeAtStation
Javadoc:
No Javadoc available
Method code:
public ChangeCargoBundleMove getChangeAtStation() {
return (ChangeCargoBundleMove) super.getMoves().get(
CHANGE_AT_STATION_INDEX);
}
Outgoing Methods (calls):
jfreerails.move.TransferCargoAtStationMove.getChangeOnTrain
Javadoc:
No Javadoc available
Method code:
public ChangeCargoBundleMove getChangeOnTrain() {
return (ChangeCargoBundleMove) super.getMoves().get(
CHANGE_ON_TRAIN_INDEX);
}
Outgoing Methods (calls):
jfreerails.move.TransferCargoAtStationMove.getPrincipal
Javadoc:
/** The player who is getting paid for the delivery. */
Method code:
/** The player who is getting paid for the delivery. */
public FreerailsPrincipal getPrincipal() {
ImList<Move> moves = super.getMoves();
for (int i = CHANGE_AT_STATION_INDEX; i < moves.size(); i++) {
if (moves.get(i) instanceof AddTransactionMove) {
AddTransactionMove move = (AddTransactionMove) moves.get(i);
return move.getPrincipal();
}
}
return Player.NOBODY;
}
Outgoing Methods (calls):
jfreerails.move.TransferCargoAtStationMove.getQuantityOfCargo
Javadoc:
No Javadoc available
Method code:
public int getQuantityOfCargo(int cargoType) {
ImList<Move> moves = super.getMoves();
int quantity = CHANGE_AT_STATION_INDEX;
for (int i = CHANGE_AT_STATION_INDEX; i < moves.size(); i++) {
if (moves.get(i) instanceof AddTransactionMove) {
AddTransactionMove move = (AddTransactionMove) moves.get(i);
DeliverCargoReceipt receipt = (DeliverCargoReceipt) move
.getTransaction();
CargoBatch cb = receipt.getCb();
if (cb.getCargoType() == cargoType) {
quantity += receipt.getQuantity();
}
}
}
return quantity;
}
Outgoing Methods (calls):
jfreerails.move.TransferCargoAtStationMove.getRevenue
Javadoc:
No Javadoc available
Method code:
public Money getRevenue() {
ImList<Move> moves = super.getMoves();
long amount = CHANGE_AT_STATION_INDEX;
for (int i = CHANGE_AT_STATION_INDEX; i < moves.size(); i++) {
if (moves.get(i) instanceof AddTransactionMove) {
AddTransactionMove move = (AddTransactionMove) moves.get(i);
DeliverCargoReceipt receipt = (DeliverCargoReceipt) move
.getTransaction();
amount += receipt.deltaCash().getAmount();
}
}
return new Money(amount);
}
Outgoing Methods (calls):
jfreerails.move.TransferCargoAtStationMove.isWaitingForFullLoad
Javadoc:
No Javadoc available
Method code:
public boolean isWaitingForFullLoad() {
return waitingForFullLoad;
}
No outgoing methods.
jfreerails.move.UndoMove.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(World w, FreerailsPrincipal p) {
return move2undo.undoMove(w, p);
}
Outgoing Methods (calls):
jfreerails.move.UndoMove.getUndoneMove
Javadoc:
No Javadoc available
Method code:
public Move getUndoneMove() {
return move2undo;
}
No outgoing methods.
jfreerails.move.UndoMove.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
return move2undo.tryUndoMove(w, p);
}
Outgoing Methods (calls):
jfreerails.move.UndoMove.tryUndoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
return move2undo.tryDoMove(w, p);
}
Outgoing Methods (calls):
jfreerails.move.UndoMove.undoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
return move2undo.undoMove(w, p);
}
Outgoing Methods (calls):
jfreerails.move.UpgradeTrackMove.generateMove
Javadoc:
No Javadoc available
Method code:
public static UpgradeTrackMove generateMove(TrackPiece before,
TrackPiece after, ImPoint p) {
ChangeTrackPieceMove m = new ChangeTrackPieceMove(before, after, p);
return new UpgradeTrackMove(m);
}
No outgoing methods.
jfreerails.move.UpgradeTrackMove.getUpdatedTiles
Javadoc:
No Javadoc available
Method code:
public Rectangle getUpdatedTiles() {
ChangeTrackPieceMove m = (ChangeTrackPieceMove) this.getMove(0);
return m.getUpdatedTiles();
}
Outgoing Methods (calls):
jfreerails.move.WorldDiffMove.doMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus doMove(World world, FreerailsPrincipal p) {
MoveStatus ms = tryMapChanges(world, false);
if (!ms.ok)
return ms;
ms = listChanges.doMove(world, p);
if (ms.isOk()) {
doMove(world, false);
}
return ms;
}
Outgoing Methods (calls):
jfreerails.move.WorldDiffMove.generate
Javadoc:
No Javadoc available
Method code:
public static WorldDiffMove generate(WorldDiffs diffs, Cause cause) {
return new WorldDiffMove(diffs.getUnderlying(), diffs, cause);
}
Outgoing Methods (calls):
jfreerails.move.WorldDiffMove.getCause
Javadoc:
No Javadoc available
Method code:
public Cause getCause() {
return cause;
}
No outgoing methods.
jfreerails.move.WorldDiffMove.getListChanges
Javadoc:
No Javadoc available
Method code:
public CompositeMove getListChanges() {
return listChanges;
}
No outgoing methods.
jfreerails.move.WorldDiffMove.getUpdatedTiles
Javadoc:
No Javadoc available
Method code:
public Rectangle getUpdatedTiles() {
return new Rectangle(x, y, w, h);
}
No outgoing methods.
jfreerails.move.WorldDiffMove.listDiffs
Javadoc:
No Javadoc available
Method code:
public int listDiffs() {
return listChanges.size();
}
Outgoing Methods (calls):
jfreerails.move.WorldDiffMove.tryDoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryDoMove(World world, FreerailsPrincipal p) {
MoveStatus ms = tryMapChanges(world, false);
if (!ms.ok)
return ms;
return ms = listChanges.tryDoMove(world, p);
}
Outgoing Methods (calls):
jfreerails.move.WorldDiffMove.tryMapChanges
Javadoc:
No Javadoc available
Method code:
private MoveStatus tryMapChanges(World world, boolean undo) {
for (int i = 0; i < diffs.size(); i++) {
MapDiff diff = diffs.get(i);
FreerailsSerializable actual = world.getTile(diff.x, diff.y);
FreerailsSerializable expected = undo ? diff.after : diff.before;
if (!actual.equals(expected)) {
return MoveStatus.moveFailed("expected =" + expected
+ ", actual = " + actual);
}
}
return MoveStatus.MOVE_OK;
}
Outgoing Methods (calls):
jfreerails.move.WorldDiffMove.tryUndoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus tryUndoMove(World world, FreerailsPrincipal p) {
MoveStatus ms = tryMapChanges(world, true);
if (!ms.ok)
return ms;
return ms = listChanges.tryUndoMove(world, p);
}
Outgoing Methods (calls):
jfreerails.move.WorldDiffMove.undoMove
Javadoc:
No Javadoc available
Method code:
public MoveStatus undoMove(World world, FreerailsPrincipal p) {
MoveStatus ms = tryMapChanges(world, true);
if (!ms.ok)
return ms;
ms = listChanges.undoMove(world, p);
if (ms.isOk()) {
doMove(world, true);
}
return ms;
}
Outgoing Methods (calls):
jfreerails.move.WorldDiffsMoveTest.runTests
Javadoc:
No Javadoc available
Method code:
void runTests() {
assertFalse(diffs.equals(world));
WorldDiffMove move = WorldDiffMove.generate(diffs, WorldDiffMove.Cause.Other);
// Doing the move on the world should also succeed.
World worldCopy = (World) Utils.cloneBySerialisation(world);
assertEquals(worldCopy, world);
MoveStatus ms = move.tryDoMove(worldCopy, fp1);
if(!ms.ok)
ms.printStackTrack();
assertTrue(ms.message, ms.ok);
ms = move.doMove(worldCopy, fp1);
assertTrue(ms.ok);
assertEquals(worldCopy, diffs);
// Undoing the move on the diffs should succeed.
WorldDiffs diffsCopy = (WorldDiffs) Utils.cloneBySerialisation(diffs);
assertEquals(diffsCopy, diffs);
ms = move.tryUndoMove(diffsCopy, fp1);
assertTrue(ms.message, ms.ok);
assertFalse(diffsCopy.equals(world));
ms = move.undoMove(diffsCopy, fp1);
assertTrue(ms.ok);
assertEquals(diffsCopy, world);
// The move should survive serialisation.
Object moveCopy = Utils.cloneBySerialisation(move);
assertEquals(moveCopy, move);
assertEquals(moveCopy.hashCode(), move.hashCode());
}
Outgoing Methods (calls):
jfreerails.move.WorldDiffsMoveTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
world = new WorldImpl(10, 10);
// Set the time..
world.set(ITEM.CALENDAR, new GameCalendar(12000, 1840));
world.addPlayer(MapFixtureFactory.TEST_PLAYER);
fp1 = world.getPlayer(0).getPrincipal();
diffs = new WorldDiffs(world);
}
Outgoing Methods (calls):
jfreerails.move.WorldDiffsMoveTest.testAddingActivateEntity
Javadoc:
No Javadoc available
Method code:
public void testAddingActivateEntity() {
Activity act = new TestActivity(30);
int row = world.addActiveEntity(fp1, act);
act = new TestActivity(40);
world.add(fp1, row, act);
act = new TestActivity(50);
diffs.add(fp1, row, act);
act = new TestActivity(60);
row = diffs.addActiveEntity(fp1, act);
act = new TestActivity(70);
diffs.add(fp1, row, act);
act = new TestActivity(80);
row = diffs.addActiveEntity(fp1, act);
act = new TestActivity(90);
diffs.add(fp1, row, act);
runTests();
}
Outgoing Methods (calls):
jfreerails.move.WorldDiffsMoveTest.testAddingActivity
Javadoc:
No Javadoc available
Method code:
public void testAddingActivity(){
Activity act = new TestActivity(30);
int row = world.addActiveEntity(fp1, act);
act = new TestActivity(40);
world.add(fp1, row, act);
act = new TestActivity(50);
diffs.add(fp1, row, act);
runTests();
}
Outgoing Methods (calls):
jfreerails.move.WorldDiffsMoveTest.testAddingElementToList
Javadoc:
No Javadoc available
Method code:
public void testAddingElementToList() {
world.add(fp1, KEY.STATIONS, city1);
diffs.add(fp1, KEY.STATIONS, city2);
diffs.add(fp1, KEY.STATIONS, city2);
diffs.add(fp1, KEY.STATIONS, city2);
runTests();
}
Outgoing Methods (calls):
jfreerails.move.WorldDiffsMoveTest.testAddingTransaction
Javadoc:
No Javadoc available
Method code:
public void testAddingTransaction() {
Transaction t1 = new AddItemTransaction(Category.BOND, 1, 1, new Money(
100));
Transaction t2 = new AddItemTransaction(Category.BOND, 2, 2, new Money(
1000));
Transaction t3 = new AddItemTransaction(Category.BOND, 3, 3, new Money(
10000));
world.addTransaction(fp1, t1);
diffs.addTransaction(fp1, t2);
diffs.addTransaction(fp1, t3);
runTests();
}
Outgoing Methods (calls):
jfreerails.move.WorldDiffsMoveTest.testChangingElementInList1
Javadoc:
No Javadoc available
Method code:
public void testChangingElementInList1() {
world.add(fp1, KEY.STATIONS, city1);
world.add(fp1, KEY.STATIONS, city1);
diffs.set(fp1, KEY.STATIONS, 0, city2);
diffs.set(fp1, KEY.STATIONS, 1, city2);
runTests();
}
Outgoing Methods (calls):
jfreerails.move.WorldDiffsMoveTest.testChangingElementInList2
Javadoc:
/** * Tests changing elements in a list by adding two cities to the world's STATIONS list, * then modifying the diffs to change those entries to city2. Verifies that the diffs * count is 2 and that the generated WorldDiffMove also has two diffs. */
Method code:
public void testChangingElementInList2() {
world.add(fp1, KEY.STATIONS, city1);
world.add(fp1, KEY.STATIONS, city1);
diffs.set(fp1, KEY.STATIONS, 0, city2);
diffs.set(fp1, KEY.STATIONS, 1, city2);
assertEquals(2, diffs.listDiffs());
WorldDiffMove move = WorldDiffMove.generate(diffs, WorldDiffMove.Cause.Other);
assertEquals(2, move.listDiffs());
}
Outgoing Methods (calls):
jfreerails.move.WorldDiffsMoveTest.testChangingMap
Javadoc:
No Javadoc available
Method code:
public void testChangingMap() {
diffs.setTile(4, 0, city1);
diffs.setTile(8, 5, city2);
runTests();
}
Outgoing Methods (calls):
jfreerails.network.AbstractEchoGameServerTestCase.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected synchronized void setUp() throws Exception {
echoGameServer = EchoGameServer.startServer();
/*
* There was a problem that occurred intermittently when the unit tests
* were run as a batch. I think it was to do with reusing ports in quick
* succession. Passing 0 as the port allow us to listen on an
* unspecified port whose number we obtain by calling getLocalPort().
* Since making this change, the problem has not occurred.
*/
server = new InetConnectionAccepter(0, echoGameServer);
Thread serverThread = new Thread(server);
serverThread.start();
}
Outgoing Methods (calls):
jfreerails.network.AbstractEchoGameServerTestCase.tearDown
Javadoc:
No Javadoc available
Method code:
@Override
protected synchronized void tearDown() throws Exception {
server.stop();
}
Outgoing Methods (calls):
jfreerails.network.AbstractInetConnection.disconnect
Javadoc:
No Javadoc available
Method code:
public void disconnect() throws IOException {
logger.fine(this + "Initiating shutdown..");
shutdownOutput();
long waitUntil = System.currentTimeMillis() + timeout;
synchronized (readerThreadStatus) {
while (readerThreadStatus.isOpen()) {
long currentTime = System.currentTimeMillis();
if (currentTime >= waitUntil) {
shutDownInput();
throw new IOException(
"Time-out while trying to disconnect.");
}
try {
readerThreadStatus.wait(timeout);
} catch (InterruptedException e) {
// do nothing.
}
}
}
logger.fine(this + "Finished shutdown!! --status="
+ String.valueOf(status.isOpen()));
}
Outgoing Methods (calls):
jfreerails.network.AbstractInetConnection.flush
Javadoc:
No Javadoc available
Method code:
public void flush() throws IOException {
inetConnection.flush();
}
Outgoing Methods (calls):
jfreerails.network.AbstractInetConnection.getThreadName
Javadoc:
No Javadoc available
Method code:
abstract String getThreadName();
No outgoing methods.
jfreerails.network.AbstractInetConnection.isOpen
Javadoc:
No Javadoc available
Method code:
public synchronized boolean isOpen() {
return status.isOpen();
}
Outgoing Methods (calls):
jfreerails.network.AbstractInetConnection.open
Javadoc:
No Javadoc available
Method code:
private synchronized void open() throws IOException {
Thread t = new Thread(this);
t.setName(getThreadName());
inetConnection.open();
t.start();
readerThreadStatus.open();
}
Outgoing Methods (calls):
jfreerails.network.AbstractInetConnection.read
Javadoc:
No Javadoc available
Method code:
FreerailsSerializable[] read() throws IOException {
if (status.isOpen()) {
return inbound.read();
}
throw new IOException();
}
Outgoing Methods (calls):
jfreerails.network.AbstractInetConnection.run
Javadoc:
No Javadoc available
Method code:
public void run() {
try {
while (true) {
FreerailsSerializable fs = inetConnection.receive();
synchronized (inbound) {
inbound.write(fs);
inbound.notifyAll();
}
}
} catch (EOFException e) {
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
logger.fine(this + "Reciprocating shutdown..");
shutDownInput();
readerThreadStatus.close();
}
Outgoing Methods (calls):
jfreerails.network.AbstractInetConnection.send
Javadoc:
No Javadoc available
Method code:
void send(FreerailsSerializable object) throws IOException {
inetConnection.send(object);
}
Outgoing Methods (calls):
jfreerails.network.AbstractInetConnection.setTimeOut
Javadoc:
No Javadoc available
Method code:
void setTimeOut(int i) {
timeout = i;
}
No outgoing methods.
jfreerails.network.AbstractInetConnection.shutDownInput
Javadoc:
No Javadoc available
Method code:
private synchronized void shutDownInput() {
try {
inetConnection.shutdownInput();
logger.fine(this + "Shut down input.");
if (status.isOpen()) {
shutdownOutput();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
Outgoing Methods (calls):
jfreerails.network.AbstractInetConnection.shutdownOutput
Javadoc:
No Javadoc available
Method code:
private synchronized void shutdownOutput() throws IOException {
if (!status.isOpen()) {
throw new IllegalStateException();
}
status.close();
inetConnection.shutdownOutput();
logger.fine(this + "Shut down output.");
}
Outgoing Methods (calls):
jfreerails.network.AbstractInetConnection.waitForObject
Javadoc:
No Javadoc available
Method code:
FreerailsSerializable waitForObject() throws InterruptedException,
IOException {
if (status.isOpen()) {
synchronized (inbound) {
if (inbound.size() > 0) {
return inbound.getFirst();
}
inbound.wait();
if (inbound.size() > 0) {
return inbound.getFirst();
}
throw new IllegalStateException();
}
}
throw new IOException("The connection is close.");
}
Outgoing Methods (calls):
jfreerails.network.Connection2Client.disconnect
Javadoc:
/** * Disconnect from the client. When this method returns, calling isOpen() on * this object returns false <b>and</b> calling isOpen() on the * corresponding Connection2Server held by the client also returns false. * * @throws IOException */
Method code:
/**
* Disconnect from the client. When this method returns, calling isOpen() on
* this object returns false <b>and</b> calling isOpen() on the
* corresponding Connection2Server held by the client also returns false.
*
* @throws IOException
*/
void disconnect() throws IOException;
No outgoing methods.
jfreerails.network.Connection2Client.flush
Javadoc:
/** Flush the underlying stream. */
Method code:
/** Flush the underlying stream. */
void flush() throws IOException;
No outgoing methods.
jfreerails.network.Connection2Client.isOpen
Javadoc:
/** Returns true if this connection is open. */
Method code:
/** Returns true if this connection is open. */
boolean isOpen();
No outgoing methods.
jfreerails.network.Connection2Client.readFromClient
Javadoc:
/** * Returns an array containing all the objects read from the client since * the last time this method or waitForObjectFromClient() was called, if no * objects have been received, it returns an empty array rather than * blocking. */
Method code:
/**
* Returns an array containing all the objects read from the client since
* the last time this method or waitForObjectFromClient() was called, if no
* objects have been received, it returns an empty array rather than
* blocking.
*/
FreerailsSerializable[] readFromClient() throws IOException;
No outgoing methods.
jfreerails.network.Connection2Client.waitForObjectFromClient
Javadoc:
/** * Returns the next object read from the client, blocking if non is * available. */
Method code:
/**
* Returns the next object read from the client, blocking if non is
* available.
*/
FreerailsSerializable waitForObjectFromClient() throws IOException,
InterruptedException;
No outgoing methods.
jfreerails.network.Connection2Client.writeToClient
Javadoc:
/** Sends the specified object to the client. */
Method code:
/** Sends the specified object to the client. */
void writeToClient(FreerailsSerializable object) throws IOException;
No outgoing methods.
jfreerails.network.Connection2Server.disconnect
Javadoc:
/** * Disconnect from the server. When this method returns, calling isOpen() on * this object returns false <b>and</b> calling isOpen() on the * corresponding Connection2Client held by the server also returns false. * * @throws IOException */
Method code:
/**
* Disconnect from the server. When this method returns, calling isOpen() on
* this object returns false <b>and</b> calling isOpen() on the
* corresponding Connection2Client held by the server also returns false.
*
* @throws IOException
*/
void disconnect() throws IOException;
No outgoing methods.
jfreerails.network.Connection2Server.flush
Javadoc:
/** Flush the underlying stream. */
Method code:
/** Flush the underlying stream. */
void flush() throws IOException;
No outgoing methods.
jfreerails.network.Connection2Server.getServerDetails
Javadoc:
No Javadoc available
Method code:
String getServerDetails();
No outgoing methods.
jfreerails.network.Connection2Server.isOpen
Javadoc:
/** Returns true if this connection is open. */
Method code:
/** Returns true if this connection is open. */
boolean isOpen();
No outgoing methods.
jfreerails.network.Connection2Server.readFromServer
Javadoc:
/** * Returns an array containing all the objects read from the server since * the last time this method or waitForObjectFromServer() was called, if no * objects have been received, it returns an empty array rather than * blocking. */
Method code:
/**
* Returns an array containing all the objects read from the server since
* the last time this method or waitForObjectFromServer() was called, if no
* objects have been received, it returns an empty array rather than
* blocking.
*/
FreerailsSerializable[] readFromServer() throws IOException;
No outgoing methods.
jfreerails.network.Connection2Server.waitForObjectFromServer
Javadoc:
/** * Returns the next object read from the server, blocking if non is * available. */
Method code:
/**
* Returns the next object read from the server, blocking if non is
* available.
*/
FreerailsSerializable waitForObjectFromServer() throws IOException,
InterruptedException;
No outgoing methods.
jfreerails.network.Connection2Server.writeToServer
Javadoc:
/** Sends the specified object to the server. */
Method code:
/** Sends the specified object to the server. */
void writeToServer(FreerailsSerializable object) throws IOException;
No outgoing methods.
jfreerails.network.EchoGameServer.addConnection
Javadoc:
No Javadoc available
Method code:
public synchronized void addConnection(Connection2Client connection) {
if (null == connection) {
throw new NullPointerException();
}
if (!status.isOpen()) {
throw new IllegalArgumentException();
}
connections.add(connection);
}
Outgoing Methods (calls):
jfreerails.network.EchoGameServer.countOpenConnections
Javadoc:
No Javadoc available
Method code:
public synchronized int countOpenConnections() {
Iterator<Connection2Client> it = connections.iterator();
while (it.hasNext()) {
Connection2Client connection = it.next();
if (!connection.isOpen()) {
it.remove();
}
}
return connections.size();
}
Outgoing Methods (calls):
jfreerails.network.EchoGameServer.run
Javadoc:
No Javadoc available
Method code:
public void run() {
status.open();
while (status.isOpen()) {
update();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// do nothing.
}
}
}
Outgoing Methods (calls):
jfreerails.network.EchoGameServer.sendMessage
Javadoc:
No Javadoc available
Method code:
synchronized void sendMessage(FreerailsSerializable m) {
/* Send messages. */
for (int i = 0; i < connections.size(); i++) {
Connection2Client connection = connections.get(i);
try {
connection.writeToClient(m);
connection.flush();
logger.fine("Sent ok: " + m);
} catch (IOException e) {
try {
if (connection.isOpen()) {
connection.disconnect();
}
} catch (IOException e1) {
// hope this doesn't happen.
e1.printStackTrace();
}
}
}
}
Outgoing Methods (calls):
jfreerails.network.EchoGameServer.startServer
Javadoc:
/** * Creates an EchoGameServer, starts it in a new Thread, and waits for its * status to change to isOpen before returning. */
Method code:
/**
* Creates an EchoGameServer, starts it in a new Thread, and waits for its
* status to change to isOpen before returning.
*/
public static EchoGameServer startServer() {
EchoGameServer server = new EchoGameServer();
Thread t = new Thread(server);
t.start();
try {
/* Wait for the server to start before returning. */
synchronized (server.status) {
server.status.wait();
}
return server;
} catch (InterruptedException e) {
e.printStackTrace();
throw new IllegalStateException();
}
}
No outgoing methods.
jfreerails.network.EchoGameServer.stop
Javadoc:
No Javadoc available
Method code:
public synchronized void stop() {
status.close();
for (int i = 0; i < connections.size(); i++) {
AbstractInetConnection connection = (AbstractInetConnection) connections
.get(i);
if (connection.isOpen()) {
try {
connection.setTimeOut(0);
connection.disconnect();
} catch (Exception e) {
// Do nothing.
}
}
}
}
Outgoing Methods (calls):
jfreerails.network.EchoGameServer.update
Javadoc:
No Javadoc available
Method code:
public void update() {
synchronized (this) {
/* Read messages. */
for (int i = 0; i < connections.size(); i++) {
Connection2Client connection = connections.get(i);
try {
FreerailsSerializable[] messages = connection
.readFromClient();
for (int j = 0; j < messages.length; j++) {
messages2send.add(messages[j]);
}
} catch (IOException e) {
try {
if (connection.isOpen()) {
connection.disconnect();
}
} catch (IOException e1) {
//
e1.printStackTrace();
}
}
}
/* Send messages. */
Iterator<FreerailsSerializable> messagesIterator = messages2send
.iterator();
while (messagesIterator.hasNext()) {
FreerailsSerializable message = messagesIterator.next();
sendMessage(message);
}
}
}
Outgoing Methods (calls):
jfreerails.network.EchoGameServerTest.testConnecting
Javadoc:
/** * Tests connecting to an EchoGameServer using instances of * InetConnection2Server. */
Method code:
/**
* Tests connecting to an EchoGameServer using instances of
* InetConnection2Server.
*/
public void testConnecting() {
try {
assertEquals(0, echoGameServer.countOpenConnections());
InetConnection2Server con1 = new InetConnection2Server(ipAddress,
server.getLocalPort());
InetConnection2Server con2 = new InetConnection2Server(ipAddress,
server.getLocalPort());
assertEquals(2, echoGameServer.countOpenConnections());
con1.writeToServer(new Money(99));
con1.flush();
FreerailsSerializable fs = con2.waitForObject();
assertEquals(new Money(99), fs);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
Outgoing Methods (calls):
jfreerails.network.GameServer.addConnection
Javadoc:
No Javadoc available
Method code:
void addConnection(Connection2Client connection);
No outgoing methods.
jfreerails.network.GameServer.countOpenConnections
Javadoc:
No Javadoc available
Method code:
int countOpenConnections();
No outgoing methods.
jfreerails.network.GameServer.stop
Javadoc:
No Javadoc available
Method code:
void stop();
No outgoing methods.
jfreerails.network.InetConnection.flush
Javadoc:
No Javadoc available
Method code:
synchronized void flush() throws IOException {
objectOutputStream.flush();
// deflaterOutputStream.flush();
// deflaterOutputStream.finish();
// deflaterOutputStream.flush();
}
No outgoing methods.
jfreerails.network.InetConnection.isOpen
Javadoc:
No Javadoc available
Method code:
synchronized boolean isOpen() {
boolean isClosed = socket.isClosed();
return !isClosed;
}
No outgoing methods.
jfreerails.network.InetConnection.open
Javadoc:
/** * Sets up the input and output streams, then sends the String * "CONNECTION_OPEN" and attempts to read the same String back. */
Method code:
/**
* Sets up the input and output streams, then sends the String
* "CONNECTION_OPEN" and attempts to read the same String back.
*/
synchronized void open() throws IOException {
OutputStream outputStream = socket.getOutputStream();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
outputStream);
// deflaterOutputStream = new DeflaterOutputStream(outputStream);
// objectOutputStream = new ObjectOutputStream(deflaterOutputStream);
objectOutputStream = new ObjectOutputStream(bufferedOutputStream);
objectOutputStream.writeObject(CONNECTION_OPEN);
objectOutputStream.flush();
InputStream inputStream = socket.getInputStream();
// inflaterInputStream = new InflaterInputStream(inputStream);
// objectInputStream = new ObjectInputStream(inflaterInputStream);
objectInputStream = new ObjectInputStream(inputStream);
try {
String s = (String) objectInputStream.readObject();
if (!s.equals(CONNECTION_OPEN)) {
throw new IllegalStateException(s);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IOException(e.getMessage());
}
}
No outgoing methods.
jfreerails.network.InetConnection.receive
Javadoc:
No Javadoc available
Method code:
FreerailsSerializable receive() throws IOException, ClassNotFoundException {
Object object = objectInputStream.readObject();
return (FreerailsSerializable) object;
}
No outgoing methods.
jfreerails.network.InetConnection.send
Javadoc:
No Javadoc available
Method code:
synchronized void send(FreerailsSerializable object) throws IOException {
objectOutputStream.writeObject(object);
flush();
}
Outgoing Methods (calls):
jfreerails.network.InetConnection.shutdownInput
Javadoc:
No Javadoc available
Method code:
synchronized void shutdownInput() throws IOException {
socket.shutdownInput();
if (socket.isInputShutdown() && socket.isOutputShutdown()) {
socket.close();
}
}
No outgoing methods.
jfreerails.network.InetConnection.shutdownOutput
Javadoc:
No Javadoc available
Method code:
synchronized void shutdownOutput() throws IOException {
socket.shutdownOutput();
if (socket.isInputShutdown() && socket.isOutputShutdown()) {
socket.close();
}
}
No outgoing methods.
jfreerails.network.InetConnection2Client.getThreadName
Javadoc:
No Javadoc available
Method code:
@Override
String getThreadName() {
return "InetConnection2Client";
}
No outgoing methods.
jfreerails.network.InetConnection2Client.readFromClient
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable[] readFromClient() throws IOException {
return read();
}
Outgoing Methods (calls):
jfreerails.network.InetConnection2Client.waitForObjectFromClient
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable waitForObjectFromClient() throws IOException,
InterruptedException {
return waitForObject();
}
Outgoing Methods (calls):
jfreerails.network.InetConnection2Client.writeToClient
Javadoc:
No Javadoc available
Method code:
public void writeToClient(FreerailsSerializable object) throws IOException {
send(object);
}
Outgoing Methods (calls):
jfreerails.network.InetConnection2Server.getServerDetails
Javadoc:
No Javadoc available
Method code:
public String getServerDetails() {
return serverDetails;
}
No outgoing methods.
jfreerails.network.InetConnection2Server.getThreadName
Javadoc:
No Javadoc available
Method code:
@Override
String getThreadName() {
return "InetConnection2Server";
}
No outgoing methods.
jfreerails.network.InetConnection2Server.readFromServer
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable[] readFromServer() throws IOException {
return read();
}
Outgoing Methods (calls):
jfreerails.network.InetConnection2Server.waitForObjectFromServer
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable waitForObjectFromServer() throws IOException,
InterruptedException {
return waitForObject();
}
Outgoing Methods (calls):
jfreerails.network.InetConnection2Server.writeToServer
Javadoc:
No Javadoc available
Method code:
public void writeToServer(FreerailsSerializable object) throws IOException {
send(object);
}
Outgoing Methods (calls):
jfreerails.network.InetConnectionAccepter.getLocalPort
Javadoc:
No Javadoc available
Method code:
public int getLocalPort() {
return serverSocket.getLocalPort();
}
No outgoing methods.
jfreerails.network.InetConnectionAccepter.isKeepRunning
Javadoc:
No Javadoc available
Method code:
private boolean isKeepRunning() {
return keepRunning.isOpen();
}
Outgoing Methods (calls):
jfreerails.network.InetConnectionAccepter.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
try {
GameServer echoGameServer = EchoGameServer.startServer();
InetConnectionAccepter accepter = new InetConnectionAccepter(6666,
echoGameServer);
Thread t = new Thread(accepter);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
Outgoing Methods (calls):
jfreerails.network.InetConnectionAccepter.run
Javadoc:
No Javadoc available
Method code:
public void run() {
Thread.currentThread().setName(
"InetConnectionAccepter, port " + serverSocket.getLocalPort());
try {
logger.fine("Accepting connections on port "
+ serverSocket.getLocalPort());
while (isKeepRunning()) {
Socket socket = serverSocket.accept();
logger.fine("Incoming connection from "
+ socket.getRemoteSocketAddress());
synchronized (this) {
synchronized (gameServer) {
InetConnection2Client connection = new InetConnection2Client(
socket);
gameServer.addConnection(connection);
}
}
}
} catch (IOException e) {
try {
stop();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
Outgoing Methods (calls):
jfreerails.network.InetConnectionAccepter.stop
Javadoc:
No Javadoc available
Method code:
public synchronized void stop() throws IOException {
this.keepRunning.close();
serverSocket.close();
// Commented out since it causes exceptions to be thrown, fixes bug
// 979831
// gameServer.stop();
}
Outgoing Methods (calls):
jfreerails.network.InetConnectionTest.testConnecting
Javadoc:
No Javadoc available
Method code:
public void testConnecting() {
try {
assertEquals(0, echoGameServer.countOpenConnections());
InetConnection connection = new InetConnection(ipAddress, server
.getLocalPort());
connection.open();
assertEquals(1, echoGameServer.countOpenConnections());
InetConnection connection2 = new InetConnection(ipAddress, server
.getLocalPort());
connection2.open();
assertEquals(2, echoGameServer.countOpenConnections());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
Outgoing Methods (calls):
jfreerails.network.LocalConnection.disconnect
Javadoc:
No Javadoc available
Method code:
public synchronized void disconnect() {
status.close();
}
Outgoing Methods (calls):
jfreerails.network.LocalConnection.flush
Javadoc:
No Javadoc available
Method code:
public void flush() {
// No need to do anything.
}
No outgoing methods.
jfreerails.network.LocalConnection.getServerDetails
Javadoc:
No Javadoc available
Method code:
public String getServerDetails() {
return SERVER_IN_SAME_JVM;
}
No outgoing methods.
jfreerails.network.LocalConnection.isOpen
Javadoc:
No Javadoc available
Method code:
public boolean isOpen() {
return status.isOpen();
}
Outgoing Methods (calls):
jfreerails.network.LocalConnection.readFromClient
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable[] readFromClient() throws IOException {
if (status.isOpen()) {
return fromClient.read();
}
throw new IOException();
}
Outgoing Methods (calls):
jfreerails.network.LocalConnection.readFromServer
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable[] readFromServer() throws IOException {
if (status.isOpen()) {
return fromServer.read();
}
throw new IOException();
}
Outgoing Methods (calls):
jfreerails.network.LocalConnection.waitForObjectFromClient
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable waitForObjectFromClient() throws IOException,
InterruptedException {
synchronized (fromClient) {
if (fromClient.size() == 0) {
fromClient.wait();
}
if (status.isOpen()) {
return fromClient.getFirst();
}
throw new IOException();
}
}
Outgoing Methods (calls):
jfreerails.network.LocalConnection.waitForObjectFromServer
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable waitForObjectFromServer() throws IOException,
InterruptedException {
if (status.isOpen()) {
synchronized (fromServer) {
if (fromServer.size() == 0) {
fromServer.wait();
}
return fromServer.getFirst();
}
}
throw new IOException();
}
Outgoing Methods (calls):
jfreerails.network.LocalConnection.writeToClient
Javadoc:
No Javadoc available
Method code:
public void writeToClient(FreerailsSerializable object) throws IOException {
if (status.isOpen()) {
synchronized (fromServer) {
fromServer.write(object);
fromServer.notifyAll();
}
} else {
throw new IOException();
}
}
Outgoing Methods (calls):
jfreerails.network.LocalConnection.writeToServer
Javadoc:
No Javadoc available
Method code:
public void writeToServer(FreerailsSerializable object) throws IOException {
if (status.isOpen()) {
synchronized (fromClient) {
fromClient.write(object);
fromClient.notifyAll();
}
} else {
throw new IOException();
}
}
Outgoing Methods (calls):
jfreerails.network.LocalConnectionTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
localConnection = new LocalConnection();
}
No outgoing methods.
jfreerails.network.LocalConnectionTest.testClose
Javadoc:
No Javadoc available
Method code:
public void testClose() {
try {
localConnection.disconnect();
Money m = new Money(100);
localConnection.writeToClient(m);
fail();
} catch (Exception e) {
}
}
Outgoing Methods (calls):
jfreerails.network.LocalConnectionTest.testIsOpen
Javadoc:
No Javadoc available
Method code:
public void testIsOpen() {
assertTrue(localConnection.isOpen());
}
Outgoing Methods (calls):
jfreerails.network.LocalConnectionTest.testReadFromClient
Javadoc:
No Javadoc available
Method code:
public void testReadFromClient() {
FreerailsSerializable[] objectsRead;
try {
objectsRead = localConnection.readFromClient();
assertNotNull(objectsRead);
assertTrue(Arrays.equals(EmptyArray, objectsRead));
Money m = new Money(100);
localConnection.writeToServer(m); // From the client.
objectsRead = localConnection.readFromClient();
FreerailsSerializable[] expectedArray = {m};
assertEquals(expectedArray.length, objectsRead.length);
assertTrue(Arrays.equals(expectedArray, objectsRead));
objectsRead = localConnection.readFromClient();
assertTrue(Arrays.equals(EmptyArray, objectsRead));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
Outgoing Methods (calls):
jfreerails.network.LocalConnectionTest.testReadFromServer
Javadoc:
No Javadoc available
Method code:
public void testReadFromServer() {
FreerailsSerializable[] objectsRead;
try {
objectsRead = localConnection.readFromServer();
assertNotNull(objectsRead);
assertTrue(Arrays.equals(EmptyArray, objectsRead));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
Outgoing Methods (calls):
jfreerails.network.LocalConnectionTest.testWait
Javadoc:
No Javadoc available
Method code:
public void testWait() {
try {
Money m = new Money(100);
localConnection.writeToServer(m);
// Since we have just added an object, there is no need to wait.
Object o = localConnection.waitForObjectFromClient();
assertEquals(m, o);
localConnection.writeToClient(m);
o = localConnection.waitForObjectFromServer();
assertEquals(m, o);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
Outgoing Methods (calls):
jfreerails.network.SynchronizedFlag.close
Javadoc:
No Javadoc available
Method code:
public synchronized void close() {
this.isOpen = false;
notifyAll();
}
No outgoing methods.
jfreerails.network.SynchronizedFlag.isOpen
Javadoc:
No Javadoc available
Method code:
public synchronized boolean isOpen() {
return isOpen;
}
No outgoing methods.
jfreerails.network.SynchronizedFlag.open
Javadoc:
No Javadoc available
Method code:
public synchronized void open() {
this.isOpen = true;
notifyAll();
}
No outgoing methods.
jfreerails.network.SynchronizedQueue.getFirst
Javadoc:
No Javadoc available
Method code:
public synchronized FreerailsSerializable getFirst() {
return queue.removeFirst();
}
No outgoing methods.
jfreerails.network.SynchronizedQueue.read
Javadoc:
No Javadoc available
Method code:
public synchronized FreerailsSerializable[] read() {
int length = queue.size();
FreerailsSerializable[] read = new FreerailsSerializable[length];
for (int i = 0; i < length; i++) {
read[i] = queue.removeFirst();
}
return read;
}
No outgoing methods.
jfreerails.network.SynchronizedQueue.size
Javadoc:
No Javadoc available
Method code:
public synchronized int size() {
return queue.size();
}
No outgoing methods.
jfreerails.network.SynchronizedQueue.write
Javadoc:
No Javadoc available
Method code:
public synchronized void write(FreerailsSerializable f) {
queue.add(f);
}
No outgoing methods.
jfreerails.network.specifics.AbstractFreerailsServerTestCase.getIpAddress
Javadoc:
No Javadoc available
Method code:
protected String getIpAddress() {
return ipAddress;
}
No outgoing methods.
jfreerails.network.specifics.AbstractFreerailsServerTestCase.getPort
Javadoc:
No Javadoc available
Method code:
protected int getPort() {
return connectionAccepter.getLocalPort();
}
Outgoing Methods (calls):
jfreerails.network.specifics.AbstractFreerailsServerTestCase.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected synchronized void setUp() throws Exception {
server = FreerailsGameServer
.startServer(new SavedGamesManager4UnitTests());
connectionAccepter = new InetConnectionAccepter(0, server);
Thread serverThread = new Thread(connectionAccepter);
serverThread.start();
}
Outgoing Methods (calls):
jfreerails.network.specifics.AbstractFreerailsServerTestCase.tearDown
Javadoc:
No Javadoc available
Method code:
@Override
protected synchronized void tearDown() throws Exception {
connectionAccepter.stop();
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClient.clientUpdates
Javadoc:
/** * Empty method called by update(), subclasses should override this method * instead of overriding update(). * */
Method code:
/**
* Empty method called by update(), subclasses should override this method
* instead of overriding update().
*
*/
protected void clientUpdates() {
}
No outgoing methods.
jfreerails.network.specifics.FreerailsClient.connect
Javadoc:
/** * Connects this client to a local server. */
Method code:
/**
* Connects this client to a local server.
*/
public final LogOnResponse connect(GameServer server, String username,
String password) {
try {
LogOnRequest request = new LogOnRequest(username, password);
connection2Server = new LocalConnection();
connection2Server.writeToServer(request);
server.addConnection((LocalConnection) connection2Server);
LogOnResponse response = (LogOnResponse) connection2Server
.waitForObjectFromServer();
return response;
} catch (Exception e) {
try {
connection2Server.disconnect();
} catch (IOException e1) {
e1.printStackTrace();
}
return LogOnResponse.rejected(e.getMessage());
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClient.disconnect
Javadoc:
/** * Disconnect the client from the server. */
Method code:
/**
* Disconnect the client from the server.
*/
public final void disconnect() {
try {
connection2Server.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClient.getLastTickTime
Javadoc:
No Javadoc available
Method code:
protected long getLastTickTime(){
return moveFork.getLastTickTime();
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClient.getMoveFork
Javadoc:
No Javadoc available
Method code:
public final MoveChainFork getMoveFork() {
return moveFork;
}
No outgoing methods.
jfreerails.network.specifics.FreerailsClient.getProperty
Javadoc:
No Javadoc available
Method code:
public final Serializable getProperty(ClientProperty propertyName) {
return properties.get(propertyName.name());
}
No outgoing methods.
jfreerails.network.specifics.FreerailsClient.getWorld
Javadoc:
No Javadoc available
Method code:
final public World getWorld() {
return world;
}
No outgoing methods.
jfreerails.network.specifics.FreerailsClient.newWorld
Javadoc:
/** * Subclasses should override this method if they need to respond the the * world being changed. */
Method code:
/**
* Subclasses should override this method if they need to respond the the
* world being changed.
*/
protected void newWorld(World w) {
}
No outgoing methods.
jfreerails.network.specifics.FreerailsClient.processMessage
Javadoc:
/** Processes a message received from the server. */
Method code:
/** Processes a message received from the server. */
final void processMessage(FreerailsSerializable message) throws IOException {
if (message instanceof Message2Client) {
Message2Client request = (Message2Client) message;
MessageStatus status = request.execute(this);
logger.fine(request.toString());
connection2Server.writeToServer(status);
} else if (message instanceof Move) {
Move m = (Move) message;
committer.fromServer(m);
moveFork.processMove(m);
} else if (message instanceof MoveStatus) {
MoveStatus ms = (MoveStatus) message;
committer.fromServer(ms);
} else if (message instanceof PreMove) {
PreMove pm = (PreMove) message;
Move m = committer.fromServer(pm);
moveFork.processMove(m);
} else if (message instanceof PreMoveStatus) {
PreMoveStatus pms = (PreMoveStatus) message;
committer.fromServer(pms);
} else {
logger.fine(message.toString());
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClient.processMove
Javadoc:
/** Sends move to the server. */
Method code:
/** Sends move to the server. */
final public void processMove(Move move) {
committer.toServer(move);
moveFork.processMove(move);
write(move);
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClient.processPreMove
Javadoc:
No Javadoc available
Method code:
public void processPreMove(PreMove pm) {
Move m = committer.toServer(pm);
moveFork.processMove(m);
write(pm);
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClient.read
Javadoc:
No Javadoc available
Method code:
final FreerailsSerializable read() {
try {
return this.connection2Server.waitForObjectFromServer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
throw new IllegalStateException();
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClient.resetProperties
Javadoc:
No Javadoc available
Method code:
public final void resetProperties(HashMap newProperties) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
No outgoing methods.
jfreerails.network.specifics.FreerailsClient.sendCommand
Javadoc:
No Javadoc available
Method code:
public void sendCommand(Message2Server c) {
write(c);
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClient.setGameModel
Javadoc:
No Javadoc available
Method code:
public final void setGameModel(FreerailsMutableSerializable o) {
world = (World) o;
committer = new MovePrecommitter(world);
newWorld(world);
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClient.setProperty
Javadoc:
No Javadoc available
Method code:
public void setProperty(ClientProperty propertyName, Serializable value) {
properties.put(propertyName.name(), value);
}
No outgoing methods.
jfreerails.network.specifics.FreerailsClient.tryDoMove
Javadoc:
/** Tests a move before sending it to the server. */
Method code:
/** Tests a move before sending it to the server. */
final public MoveStatus tryDoMove(Move move) {
return move.tryDoMove(world, Player.AUTHORITATIVE);
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClient.update
Javadoc:
/** Reads and deals with all outstanding messages from the server. */
Method code:
/** Reads and deals with all outstanding messages from the server. */
final public void update() {
try {
FreerailsSerializable[] messages = connection2Server
.readFromServer();
for (int i = 0; i < messages.length; i++) {
FreerailsSerializable message = messages[i];
processMessage(message);
}
connection2Server.flush();
clientUpdates();
} catch (IOException e) {
ReportBugTextGenerator.unexpectedException(e);
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClient.write
Javadoc:
No Javadoc available
Method code:
final void write(FreerailsSerializable fs) {
try {
connection2Server.writeToServer(fs);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException();
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClientTest.assertConnectClientsEquals
Javadoc:
No Javadoc available
Method code:
private void assertConnectClientsEquals(FreerailsClient client,
ImStringList expectedPlayerNames) throws IOException,
InterruptedException {
Message2Client message2Client = (Message2Client) client.read();
message2Client.execute(client);
ImStringList actualPlayerNames = (ImStringList) client
.getProperty(ClientProperty.CONNECTED_CLIENTS);
assertNotNull(actualPlayerNames);
assertEquals(expectedPlayerNames, actualPlayerNames);
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClientTest.assertMapsAndSaveGamesReceived
Javadoc:
No Javadoc available
Method code:
private void assertMapsAndSaveGamesReceived(FreerailsClient client)
throws IOException, InterruptedException {
// 2 commands to read.
Message2Client message2Client = (Message2Client) client.read();
message2Client.execute(client);
message2Client = (Message2Client) client.read();
message2Client.execute(client);
Object maps = client.getProperty(ClientProperty.MAPS_AVAILABLE);
assertNotNull(maps);
Object savedGames = client
.getProperty(ClientProperty.SAVED_GAMES);
assertNotNull(savedGames);
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClientTest.testLogon
Javadoc:
No Javadoc available
Method code:
public void testLogon() {
try {
/* Test 1 : connecting a client. */
assertEquals("No client connected yet.", 0, server
.countOpenConnections());
FreerailsClient client = new FreerailsClient();
LogOnResponse response = client.connect(getIpAddress(), getPort(),
"name", "password");
assertTrue(response.isSuccessful());
assertEquals(1, server.countOpenConnections());
assertMapsAndSaveGamesReceived(client);
assertConnectClientsEquals(client, new ImStringList("name"));
/* Test 2 : a client that has already logged on. */
FreerailsClient client2 = new FreerailsClient();
response = client2.connect(getIpAddress(), getPort(), "name",
"password");
assertFalse("The player is already logged on.", response
.isSuccessful());
assertEquals(1, server.countOpenConnections());
/* Test 3 : connecting a client. */
FreerailsClient client3 = new FreerailsClient();
response = client3.connect(getIpAddress(), getPort(), "name3",
"password");
assertTrue(response.isSuccessful());
assertEquals(2, server.countOpenConnections());
/* read list of connected clients. */
assertConnectClientsEquals(client,
new ImStringList("name", "name3"));
assertMapsAndSaveGamesReceived(client3);
assertConnectClientsEquals(client3, new ImStringList("name",
"name3"));
/* Test 4 : disconnect the client from test 1. */
client.disconnect();
assertEquals(1, server.countOpenConnections());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClientWithLocalServerTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
savedGamesManager = new SavedGamesManager4UnitTests();
server = new FreerailsGameServer(savedGamesManager);
}
No outgoing methods.
jfreerails.network.specifics.FreerailsClientWithLocalServerTest.testLoadingGame
Javadoc:
No Javadoc available
Method code:
public void testLoadingGame() {
try {
int commandID = 0;
// Add client to server.
FreerailsClient client0 = new FreerailsClient();
LogOnResponse response0 = client0.connect(server, "client0",
"password");
assertTrue(response0.isSuccessful());
client0.update();
// Start game
ImStringList mapNames = (ImStringList) client0
.getProperty(ClientProperty.MAPS_AVAILABLE);
Message2Server newGameMessage2 = new NewGameMessage2Server(
commandID++, mapNames.get(0));
MessageStatus cm = newGameMessage2.execute(server);
assertTrue(cm.isSuccessful());
// Save game and stop server
String savedGameName = "game1";
Message2Server saveGameMessage2 = new SaveGameMessage2Server(
commandID++, savedGameName);
cm = saveGameMessage2.execute(server);
assertTrue(cm.isSuccessful());
server.stopGame();
// Start 2nd server with saved game
server = new FreerailsGameServer(savedGamesManager);
server.loadgame(savedGameName);
assertEquals(0, server.countOpenConnections());
// Attempt to attach invalid player.
client0 = new FreerailsClient();
response0 = client0.connect(server, "client0", "batman");
assertFalse("bad password", response0.isSuccessful());
assertEquals(0, server.countOpenConnections());
response0 = client0.connect(server, "client1", "password");
assertFalse("bad username", response0.isSuccessful());
assertEquals(0, server.countOpenConnections());
response0 = client0.connect(server, "client0", "password");
assertTrue("Ok, same username and password as before.", response0
.isSuccessful());
assertEquals(1, server.countOpenConnections());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClientWithLocalServerTest.testLogon
Javadoc:
/** Copy & pasted from FreerailsClientTest, then edited. */
Method code:
/** Copy & pasted from FreerailsClientTest, then edited. */
public void testLogon() {
try {
/* Test 1 : connecting a client. */
assertEquals("No client connected yet.", 0, server
.countOpenConnections());
FreerailsClient client = new FreerailsClient();
LogOnResponse response = client.connect(server, "name", "password");
assertTrue(response.isSuccessful());
assertEquals(1, server.countOpenConnections());
// Check the client gets its properties updated.
client.update();
assertNotNull(client
.getProperty(ClientControlInterface.ClientProperty.CONNECTED_CLIENTS));
assertNotNull(client
.getProperty(ClientControlInterface.ClientProperty.MAPS_AVAILABLE));
assertNotNull(client
.getProperty(ClientControlInterface.ClientProperty.SAVED_GAMES));
/* Test 2 : a client that has already logged on. */
FreerailsClient client1 = new FreerailsClient();
response = client1.connect(server, "name", "password");
assertFalse("The player is already logged on.", response
.isSuccessful());
assertEquals(1, server.countOpenConnections());
/* Test 3 : connecting a client. */
FreerailsClient client3 = new FreerailsClient();
response = client3.connect(server, "name3", "password");
assertTrue(response.isSuccessful());
assertEquals(2, server.countOpenConnections());
/* Test 4 : disconnect the client from test 1. */
client.disconnect();
assertEquals(1, server.countOpenConnections());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClientWithLocalServerTest.testNewGame
Javadoc:
No Javadoc available
Method code:
public void testNewGame() {
assertEquals(0, server.countOpenConnections());
/* Connect 2 clients. */
FreerailsClient client0 = new FreerailsClient();
LogOnResponse response0 = client0
.connect(server, "client0", "password");
assertTrue(response0.isSuccessful());
FreerailsClient client1 = new FreerailsClient();
LogOnResponse response1 = client1
.connect(server, "client1", "password");
assertTrue(response1.isSuccessful());
assertEquals(2, server.countOpenConnections());
client0.update();
client1.update();
/* Start a new game. */
assertNull(client0.getWorld());
assertNull(client1.getWorld());
ImStringList mapNames = (ImStringList) client0
.getProperty(ClientProperty.MAPS_AVAILABLE);
final int commandID = 66;
Message2Server message2 = new NewGameMessage2Server(commandID, mapNames
.get(0));
client0.write(message2);
assertTrue(server.isNewPlayersAllowed());
server.update();
assertFalse("New players cannot be added once the game has started.",
server.isNewPlayersAllowed());
/*
* Note, the following would have happened anyway when client0.update();
* gets called.
*/
FreerailsSerializable obj = client0.read();
Message2Client cc = (Message2Client) obj;
client0.write(cc.execute(client0));
obj = client0.read();
MessageStatus status = (MessageStatus) obj;
assertTrue(status.isSuccessful());
assertEquals(commandID, status.getId());
/* The server should have sent a message2 that sets the world object. */
client0.update();
client1.update();
assertNotNull(client0.getWorld());
assertNotNull(client1.getWorld());
/* The server will not have read the players confirmation yet. */
assertFalse(server.isConfirmed(0));
assertFalse(server.isConfirmed(1));
server.update();
/* Now it will. */
assertTrue(server.isConfirmed(0));
assertTrue(server.isConfirmed(1));
/*
* The number of players on the world object should be the same as the
* number of players under the ClientControlInterface.CONNECTED_CLIENTS
* key
*/
int connectedPlayers = ((ImStringList) client0
.getProperty(ClientProperty.CONNECTED_CLIENTS)).size();
int playersOnWorldObject = client0.getWorld().getNumberOfPlayers();
assertEquals(connectedPlayers, playersOnWorldObject);
World w = client0.getWorld();
assertNotNull(w.getPlayer(0));
assertNotNull(w.getPlayer(1));
/*
* Now check that attempts to log on by new players are rejected.
*/
assertEquals(2, server.countOpenConnections());
FreerailsClient client = new FreerailsClient();
LogOnResponse response = client.connect(server, "Late player",
"password");
assertFalse(response.isSuccessful());
assertEquals(2, server.countOpenConnections());
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClientWithLocalServerTest.testSendingMoves
Javadoc:
/** Tests sending moves between client and server. */
Method code:
/** Tests sending moves between client and server. */
public void testSendingMoves() {
try {
/* Set up and start a game with 2 clients. */
FreerailsClient client0 = new FreerailsClient();
LogOnResponse response0 = client0.connect(server, "client0",
"password");
assertTrue(response0.isSuccessful());
FreerailsClient client1 = new FreerailsClient();
LogOnResponse response1 = client1.connect(server, "client1",
"password");
assertTrue(response1.isSuccessful());
client0.update();
client1.update();
ImStringList mapNames = (ImStringList) client0
.getProperty(ClientProperty.MAPS_AVAILABLE);
Message2Server message2 = new NewGameMessage2Server(99, mapNames
.get(0));
client0.write(message2);
server.update();
client0.update();
client1.update();
/* Now try sending some moves. */
World world = client0.getWorld();
Player player0 = world.getPlayer(0);
FreerailsPrincipal principal0 = player0.getPrincipal();
Transaction t = new Receipt(new Money(100),
Transaction.Category.MISC_INCOME);
Move move = new AddTransactionMove(principal0, t);
World copyOfWorld = world.defensiveCopy();
assertEquals(copyOfWorld, world);
MoveStatus status = move.doMove(copyOfWorld, principal0);
assertTrue(status.isOk());
// client0.write(move);
client0.processMove(move);
server.update();
MoveStatus reply = (MoveStatus) client0.read();
assertEquals(MoveStatus.MOVE_OK, reply);
client0.processMessage(reply);
/*
* After performing an update, the server and 2 clients' copies of
* the world object should be in the same state.
*/
server.update();
client0.update();
client1.update();
assertEquals(copyOfWorld, world);
assertEquals(copyOfWorld, client1.getWorld());
assertEquals(copyOfWorld, server.getCopyOfWorld());
/* Test disconnecting and reconnecting during play. */
client0.disconnect();
client1.processMove(move);
// client1.write(move);
move.doMove(client1.getWorld(), principal0);
client1.update();
server.update();
client1.update();
assertFalse(world.equals(client1.getWorld()));
response0 = client0.connect(server, "client0", "password");
assertTrue(response0.isSuccessful());
assertEquals(0, response0.getPlayerID());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsClientWithLocalServerTest.testSendingPreMoves
Javadoc:
/** Tests sending premoves between client and server. */
Method code:
/** Tests sending premoves between client and server. */
public void testSendingPreMoves() {
try {
/* Set up and start a game with 2 clients. */
FreerailsClient client0 = new FreerailsClient();
LogOnResponse response0 = client0.connect(server, "client0",
"password");
assertTrue(response0.isSuccessful());
FreerailsClient client1 = new FreerailsClient();
LogOnResponse response1 = client1.connect(server, "client1",
"password");
assertTrue(response1.isSuccessful());
client0.update();
client1.update();
ImStringList mapNames = (ImStringList) client0
.getProperty(ClientProperty.MAPS_AVAILABLE);
Message2Server message2 = new NewGameMessage2Server(99, mapNames
.get(0));
client0.write(message2);
server.update();
client0.update();
client1.update();
/* Now try sending some premoves. */
Player player0 = client0.getWorld().getPlayer(0);
FreerailsPrincipal principal0 = player0.getPrincipal();
PreMove pm = TimeTickPreMove.INSTANCE;
World copyOfWorld = client0.getWorld().defensiveCopy();
assertEquals(copyOfWorld, client0.getWorld());
Move move = pm.generateMove(copyOfWorld);
MoveStatus status = move.doMove(copyOfWorld, principal0);
assertTrue(status.isOk());
client0.processPreMove(pm);
server.update();
PreMoveStatus reply = (PreMoveStatus) client0.read();
assertEquals(PreMoveStatus.PRE_MOVE_OK, reply);
client0.processMessage(reply);
server.update();
client0.update();
client1.update();
assertEquals(copyOfWorld, client0.getWorld());
assertEquals(copyOfWorld, client1.getWorld());
assertEquals(copyOfWorld, server.getCopyOfWorld());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.addConnection
Javadoc:
No Javadoc available
Method code:
public synchronized void addConnection(Connection2Client connection) {
String[] before = getPlayerNames();
logger.fine("Adding connection..");
logger.fine("Waiting for login details..");
try {
LogOnRequest request = (LogOnRequest) connection
.waitForObjectFromClient();
logger.fine("Trying to login player: " + request.getUsername());
LogOnResponse response = this.logon(request);
connection.writeToClient(response);
connection.flush();
NameAndPassword p = new NameAndPassword(request.getUsername(),
request.getPassword());
if (response.isSuccessful()) {
logger.fine("Login successful");
synchronized (acceptedConnections) {
acceptedConnections.put(p, connection);
}
/* Just send to the new client. */
Message2Client setMaps = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.MAPS_AVAILABLE,
new ImStringList(savedGamesManager.getNewMapNames()));
ImStringList savedGameNames = new ImStringList(
savedGamesManager.getSaveGameNames());
Message2Client setSaveGames = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.SAVED_GAMES, savedGameNames);
connection.writeToClient(setMaps);
connection.writeToClient(setSaveGames);
// no need to flush since it is done in
// sendListOfConnectedPlayers2Clients()
/*
* If there is a game in progress, we need to send the client a
* copy of the world object.
*/
if (null != serverGameModel && null != getWorld()) {
SetWorldMessage2Client command = new SetWorldMessage2Client(
confirmationID, getWorld());
connection.writeToClient(command);
}
/* Send to all clients. */
sendListOfConnectedPlayers2Clients();
String[] after = getPlayerNames();
propertyChangeSupport.firePropertyChange("CONNECTED_PLAYERS",
before, after);
} else {
connection.disconnect();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.addPropertyChangeListener
Javadoc:
No Javadoc available
Method code:
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
No outgoing methods.
jfreerails.network.specifics.FreerailsGameServer.countOpenConnections
Javadoc:
No Javadoc available
Method code:
public synchronized int countOpenConnections() {
Iterator<NameAndPassword> it = acceptedConnections.keySet().iterator();
int numConnections = 0;
while (it.hasNext()) {
Connection2Client connection = acceptedConnections.get(it.next());
if (connection.isOpen()) {
numConnections++;
}
}
return numConnections;
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.getCopyOfWorld
Javadoc:
No Javadoc available
Method code:
World getCopyOfWorld() {
return this.getWorld().defensiveCopy();
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.getNextClientCommandId
Javadoc:
No Javadoc available
Method code:
private int getNextClientCommandId() {
return commandID++;
}
No outgoing methods.
jfreerails.network.specifics.FreerailsGameServer.getPlayerNames
Javadoc:
No Javadoc available
Method code:
public String[] getPlayerNames() {
String[] playerNames = new String[players.size()];
for (int i = 0; i < players.size(); i++) {
playerNames[i] = players.get(i).username;
}
return playerNames;
}
No outgoing methods.
jfreerails.network.specifics.FreerailsGameServer.getWorld
Javadoc:
No Javadoc available
Method code:
private World getWorld() {
return serverGameModel.getWorld();
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.isConfirmed
Javadoc:
No Javadoc available
Method code:
boolean isConfirmed(int player) {
logger.fine("confirmedPlayers.size()=" + confirmedPlayers.size());
boolean isConfirmed = confirmedPlayers.contains(players.get(player));
return isConfirmed;
}
No outgoing methods.
jfreerails.network.specifics.FreerailsGameServer.isNewPlayersAllowed
Javadoc:
No Javadoc available
Method code:
public boolean isNewPlayersAllowed() {
return newPlayersAllowed;
}
No outgoing methods.
jfreerails.network.specifics.FreerailsGameServer.isPlayer
Javadoc:
No Javadoc available
Method code:
private boolean isPlayer(String username) {
for (NameAndPassword p : players) {
if (p.username.equals(username))
return true;
}
return false;
}
No outgoing methods.
jfreerails.network.specifics.FreerailsGameServer.loadgame
Javadoc:
No Javadoc available
Method code:
public void loadgame(String saveGameName) throws IOException {
logger.info("load game " + saveGameName);
newPlayersAllowed = false;
confirmedPlayers.clear();
ServerGameModel loadedGame;
loadedGame = (ServerGameModel) savedGamesManager.loadGame(saveGameName);
String[] passwords = loadedGame.getPasswords();
World w = loadedGame.getWorld();
assert passwords.length == w.getNumberOfPlayers();
ArrayList<NameAndPassword> newPlayers = new ArrayList<NameAndPassword>();
for (int i = 0; i < passwords.length; i++) {
Player player = w.getPlayer(i);
NameAndPassword nap = new NameAndPassword(player.getName(),
passwords[i]);
newPlayers.add(nap);
}
/*
* Remove any currently logged on players who are not participants in
* the game we are loading.
*/
for (NameAndPassword nap : players) {
if (!newPlayers.contains(nap) && currentlyLoggedOn.contains(nap)) {
removeConnection(nap);
}
}
players = newPlayers;
setServerGameModel(loadedGame);
sendWorldUpdatedCommand();
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.logoff
Javadoc:
/** * Logs off a player by removing their NameAndPassword entry from the currently logged-on collection. * * @param player the index of the player in the players list to be logged off * @throws IndexOutOfBoundsException if the player index is out of bounds */
Method code:
public void logoff(int player) {
NameAndPassword np = players.get(player);
currentlyLoggedOn.remove(np);
}
No outgoing methods.
jfreerails.network.specifics.FreerailsGameServer.logon
Javadoc:
No Javadoc available
Method code:
public LogOnResponse logon(LogOnRequest lor) {
NameAndPassword p = new NameAndPassword(lor.getUsername(), lor
.getPassword());
boolean isReturningPlayer = isPlayer(lor.getUsername());
if (!this.newPlayersAllowed && !isReturningPlayer) {
return LogOnResponse.rejected("New logins not allowed.");
}
if (currentlyLoggedOn.contains(p)) {
return LogOnResponse.rejected("Already logged on.");
}
if (isReturningPlayer) {
if (!players.contains(p)) {
return LogOnResponse.rejected("Incorrect password.");
}
} else {
players.add(p);
}
currentlyLoggedOn.add(p);
return LogOnResponse.accepted(players.indexOf(p));
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.newGame
Javadoc:
No Javadoc available
Method code:
public void newGame(String mapName) {
newPlayersAllowed = false;
confirmedPlayers.clear();
try {
World world = (World) savedGamesManager.newMap(mapName);
String[] passwords = new String[players.size()];
/* Add players to world. */
for (int i = 0; i < players.size(); i++) {
String name = players.get(i).username;
Player p = new Player(name, i);
Move addPlayerMove = AddPlayerMove.generateMove(world, p);
MoveStatus ms = addPlayerMove.doMove(world, Player.AUTHORITATIVE);
if(!ms.ok) throw new IllegalStateException();
passwords[i] = players.get(i).password;
}
serverGameModel.setWorld(world, passwords);
setServerGameModel(serverGameModel);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendWorldUpdatedCommand();
logger.fine("newGame");
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.refreshSavedGames
Javadoc:
No Javadoc available
Method code:
public void refreshSavedGames() {
Message2Client setMaps = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.MAPS_AVAILABLE,
new ImStringList(savedGamesManager.getNewMapNames()));
ImStringList savedGameNames = new ImStringList(
savedGamesManager.getSaveGameNames());
Message2Client setSaveGames = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.SAVED_GAMES, savedGameNames);
send2All(setMaps);
send2All(setSaveGames);
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.removeConnection
Javadoc:
No Javadoc available
Method code:
private void removeConnection(NameAndPassword p) throws IOException {
String[] before = getPlayerNames();
Connection2Client connection = acceptedConnections.get(p);
/*
* Fix for bug 1047439 Shutting down remote client crashes server We get
* an IllegalStateException if we try to disconnect a connection that is
* not open.
*/
if (connection.isOpen()) {
connection.disconnect();
}
this.currentlyLoggedOn.remove(p);
String[] after = getPlayerNames();
propertyChangeSupport.firePropertyChange("CONNECTED_PLAYERS", before,
after);
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.removePropertyChangeListener
Javadoc:
No Javadoc available
Method code:
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
No outgoing methods.
jfreerails.network.specifics.FreerailsGameServer.run
Javadoc:
No Javadoc available
Method code:
public void run() {
status.open();
status.close();
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.savegame
Javadoc:
No Javadoc available
Method code:
public void savegame(String saveGameName) {
logger.info("save game as " + saveGameName);
try {
savedGamesManager.saveGame(serverGameModel, saveGameName);
String[] saves = savedGamesManager.getSaveGameNames();
Message2Client request = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.SAVED_GAMES, new ImStringList(
saves));
send2All(request);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.send2All
Javadoc:
No Javadoc available
Method code:
private void send2All(FreerailsSerializable message) {
send2AllExcept(null, message);
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.send2AllExcept
Javadoc:
/** Sends the specified message to all connections except the specified one. */
Method code:
/** Sends the specified message to all connections except the specified one. */
private void send2AllExcept(Connection2Client dontSend2,
FreerailsSerializable message) {
Iterator<NameAndPassword> it = acceptedConnections.keySet().iterator();
while (it.hasNext()) {
NameAndPassword p = it.next();
Connection2Client connection = acceptedConnections.get(p);
if (dontSend2 != connection) {
try {
connection.writeToClient(message);
connection.flush();
} catch (Exception e) {
if (connection.isOpen()) {
e.printStackTrace();
try {
removeConnection(p);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.sendListOfConnectedPlayers2Clients
Javadoc:
No Javadoc available
Method code:
private void sendListOfConnectedPlayers2Clients() throws IOException {
/* Send the client the list of players. */
String[] playerNames = getPlayerNames();
Message2Client request = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.CONNECTED_CLIENTS, new ImStringList(
playerNames));
send2All(request);
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.sendWorldUpdatedCommand
Javadoc:
No Javadoc available
Method code:
private void sendWorldUpdatedCommand() {
/* Send the world to the clients. */
confirmationID = getNextClientCommandId();
SetWorldMessage2Client command = new SetWorldMessage2Client(
confirmationID, getWorld());
send2All(command);
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.setNewPlayersAllowed
Javadoc:
No Javadoc available
Method code:
public void setNewPlayersAllowed(boolean newPlayersAllowed) {
this.newPlayersAllowed = newPlayersAllowed;
}
No outgoing methods.
jfreerails.network.specifics.FreerailsGameServer.setServerGameModel
Javadoc:
No Javadoc available
Method code:
public void setServerGameModel(ServerGameModel serverGameModel) {
this.serverGameModel = serverGameModel;
MoveReceiver moveExecutor = new MoveReceiver() {
public void processMove(Move move) {
MoveStatus ms = move.doMove(getWorld(), Player.AUTHORITATIVE);
if (ms.ok) {
send2All(move);
} else {
logger.warning(ms.message);
}
}
};
serverGameModel.init(moveExecutor);
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServer.startServer
Javadoc:
No Javadoc available
Method code:
public static FreerailsGameServer startServer(SavedGamesManager gamesManager) {
FreerailsGameServer server = new FreerailsGameServer(gamesManager);
Thread t = new Thread(server);
t.start();
try {
/* Wait for the server to start before returning. */
synchronized (server.status) {
server.status.wait();
}
return server;
} catch (InterruptedException e) {
e.printStackTrace();
throw new IllegalStateException();
}
}
No outgoing methods.
jfreerails.network.specifics.FreerailsGameServer.stop
Javadoc:
No Javadoc available
Method code:
public void stop() {
// TODO Auto-generated method stub
}
No outgoing methods.
jfreerails.network.specifics.FreerailsGameServer.stopGame
Javadoc:
No Javadoc available
Method code:
public void stopGame() {
logger.info("Stop game.");
}
No outgoing methods.
jfreerails.network.specifics.FreerailsGameServer.update
Javadoc:
/** * Updates the game model, then reads and deals with the outstanding * messages from each of the connected clients. This method is synchronized * to prevent moves being sent out while addConnection(.) is executing. */
Method code:
/**
* Updates the game model, then reads and deals with the outstanding
* messages from each of the connected clients. This method is synchronized
* to prevent moves being sent out while addConnection(.) is executing.
*/
public synchronized void update() {
if (null != serverGameModel) {
serverGameModel.update();
}
try {
Iterator<NameAndPassword> it = acceptedConnections.keySet()
.iterator();
while (it.hasNext()) {
NameAndPassword player = it.next();
Connection2Client connection = acceptedConnections.get(player);
if (connection.isOpen()) {
FreerailsSerializable[] messages = connection
.readFromClient();
for (int i = 0; i < messages.length; i++) {
if (messages[i] instanceof Message2Server) {
Message2Server message2 = (Message2Server) messages[i];
MessageStatus cStatus = message2.execute(this);
logger.fine(message2.toString());
connection.writeToClient(cStatus);
} else if (messages[i] instanceof MessageStatus) {
MessageStatus messageStatus = (MessageStatus) messages[i];
if (messageStatus.getId() == this.confirmationID) {
/*
* The client is confirming that they have
* updated their world object to the current
* version.
*/
this.confirmedPlayers.add(player);
logger.fine("Confirmed player " + player);
}
logger.fine(messages[i].toString());
} else if (messages[i] instanceof Move
|| messages[i] instanceof PreMove) {
Player player2 = getWorld().getPlayer(
players.indexOf(player));
FreerailsPrincipal principal = player2
.getPrincipal();
Move move;
boolean isMove = messages[i] instanceof Move;
if (isMove) {
move = (Move) messages[i];
} else {
PreMove pm = (PreMove) messages[i];
move = pm.generateMove(getWorld());
}
MoveStatus mStatus = move.tryDoMove(
this.getWorld(), principal);
if (mStatus.isOk()) {
move.doMove(getWorld(), principal);
/*
* We don't send the move to the client that
* submitted it.
*/
send2AllExcept(connection, move);
}
if (isMove) {
connection.writeToClient(mStatus);
} else {
connection.writeToClient(PreMoveStatus
.fromMoveStatus(mStatus));
}
} else {
logger.fine(messages[i].toString());
}
}
connection.flush();
} else {
/* Remove connection. */
this.removeConnection(player);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.FreerailsGameServerTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
server = new FreerailsGameServer(new SavedGamesManager4UnitTests());
}
No outgoing methods.
jfreerails.network.specifics.FreerailsGameServerTest.testLogon
Javadoc:
No Javadoc available
Method code:
public void testLogon() {
LogOnResponse response;
/* Test 1 */
LogOnRequest request1 = new LogOnRequest("Name", "password");
response = server.logon(request1);
assertTrue("Simple case, should go through.", response.isSuccessful());
assertEquals("1st logon is player 0", 0, response.getPlayerID());
/* Test 2 */
LogOnRequest request2 = new LogOnRequest("Name2", "password2");
response = server.logon(request2);
assertTrue("Simple case, should go through.", response.isSuccessful());
assertEquals("2nd logon is player 1", 1, response.getPlayerID());
/* Test 3: When player is already logged on. */
LogOnRequest request3 = new LogOnRequest("Name", "password");
response = server.logon(request3);
assertFalse("Player is already logged on.", response.isSuccessful());
/* Test 4: When new logons are not allowed. */
server.setNewPlayersAllowed(false);
LogOnRequest request4 = new LogOnRequest("Name4", "password4");
response = server.logon(request4);
assertFalse("New logons are not allowed.", response.isSuccessful());
/* Test 5: When the player has logged off, then tries to log on. */
server.logoff(0);
LogOnRequest request5 = request1;
response = server.logon(request5);
assertTrue("Player 0 has logged off, so should succeed.", response
.isSuccessful());
assertEquals("Should keep the same player id", 0, response
.getPlayerID());
/*
* Test 6: When the player has logged off, then tries to log on with
* wrong password.
*/
server.logoff(0);
LogOnRequest request6 = new LogOnRequest("Name", "batman");
response = server.logon(request6);
assertFalse("Player 0 has logged off, but the password is wrong.",
response.isSuccessful());
}
Outgoing Methods (calls):
jfreerails.network.specifics.LoadGameMessage2Server.execute
Javadoc:
No Javadoc available
Method code:
public MessageStatus execute(ServerControlInterface server) {
try {
server.loadgame(filename);
return new MessageStatus(id, true);
} catch (Exception e) {
e.printStackTrace();
return new MessageStatus(id, false, e.getMessage());
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.LoadGameMessage2Server.getID
Javadoc:
No Javadoc available
Method code:
public int getID() {
return id;
}
No outgoing methods.
jfreerails.network.specifics.LogOnRequest.getPassword
Javadoc:
No Javadoc available
Method code:
public String getPassword() {
return password;
}
No outgoing methods.
jfreerails.network.specifics.LogOnRequest.getUsername
Javadoc:
/** Returns the username associated with this log-on request. @return the username */
Method code:
public String getUsername() {
return username;
}
No outgoing methods.
jfreerails.network.specifics.LogOnResponse.accepted
Javadoc:
No Javadoc available
Method code:
public static LogOnResponse accepted(int playerNumber) {
return new LogOnResponse(true, playerNumber, null);
}
No outgoing methods.
jfreerails.network.specifics.LogOnResponse.getMessage
Javadoc:
No Javadoc available
Method code:
public String getMessage() {
return message;
}
No outgoing methods.
jfreerails.network.specifics.LogOnResponse.getPlayerID
Javadoc:
No Javadoc available
Method code:
public int getPlayerID() {
return playerNumber;
}
No outgoing methods.
jfreerails.network.specifics.LogOnResponse.isSuccessful
Javadoc:
No Javadoc available
Method code:
public boolean isSuccessful() {
return successful;
}
No outgoing methods.
jfreerails.network.specifics.LogOnResponse.rejected
Javadoc:
No Javadoc available
Method code:
public static LogOnResponse rejected(String reason) {
return new LogOnResponse(false, -1, reason);
}
No outgoing methods.
jfreerails.network.specifics.MoveChainFork.addCompleteMoveReceiver
Javadoc:
No Javadoc available
Method code:
public void addCompleteMoveReceiver(MoveReceiver moveReceiver) {
if (null == moveReceiver) {
throw new NullPointerException();
}
moveReceivers.add(moveReceiver);
}
No outgoing methods.
jfreerails.network.specifics.MoveChainFork.addListListener
Javadoc:
No Javadoc available
Method code:
public void addListListener(WorldListListener listener) {
if (null == listener) {
throw new NullPointerException();
}
listListeners.add(listener);
}
No outgoing methods.
jfreerails.network.specifics.MoveChainFork.addMapListener
Javadoc:
No Javadoc available
Method code:
public void addMapListener(WorldMapListener l) {
mapListeners.add(l);
}
No outgoing methods.
jfreerails.network.specifics.MoveChainFork.addSplitMoveReceiver
Javadoc:
No Javadoc available
Method code:
public void addSplitMoveReceiver(MoveReceiver moveReceiver) {
if (null == moveReceiver) {
throw new NullPointerException();
}
splitMoveReceivers.add(moveReceiver);
}
No outgoing methods.
jfreerails.network.specifics.MoveChainFork.getLastTickTime
Javadoc:
No Javadoc available
Method code:
public long getLastTickTime() {
return lastTickTime;
}
No outgoing methods.
jfreerails.network.specifics.MoveChainFork.processMove
Javadoc:
No Javadoc available
Method code:
public void processMove(Move move) {
for (int i = 0; i < moveReceivers.size(); i++) {
MoveReceiver m = moveReceivers.get(i);
m.processMove(move);
}
splitMove(move);
}
Outgoing Methods (calls):
jfreerails.network.specifics.MoveChainFork.removeCompleteMoveReceiver
Javadoc:
No Javadoc available
Method code:
public void removeCompleteMoveReceiver(MoveReceiver moveReceiver) {
if (null == moveReceiver) {
throw new NullPointerException();
}
moveReceivers.remove(moveReceiver);
}
No outgoing methods.
jfreerails.network.specifics.MoveChainFork.removeMapListener
Javadoc:
No Javadoc available
Method code:
public void removeMapListener(WorldMapListener l) {
mapListeners.remove(l);
}
No outgoing methods.
jfreerails.network.specifics.MoveChainFork.sendItemAdded
Javadoc:
No Javadoc available
Method code:
private void sendItemAdded(KEY key, int index, FreerailsPrincipal p) {
for (int i = 0; i < listListeners.size(); i++) {
WorldListListener l = listListeners.get(i);
l.itemAdded(key, index, p);
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.MoveChainFork.sendItemRemoved
Javadoc:
No Javadoc available
Method code:
private void sendItemRemoved(KEY key, int index, FreerailsPrincipal p) {
for (int i = 0; i < listListeners.size(); i++) {
WorldListListener l = listListeners.get(i);
l.itemRemoved(key, index, p);
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.MoveChainFork.sendListUpdated
Javadoc:
No Javadoc available
Method code:
private void sendListUpdated(KEY key, int index, FreerailsPrincipal p) {
for (int i = 0; i < listListeners.size(); i++) {
WorldListListener l = listListeners.get(i);
l.listUpdated(key, index, p);
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.MoveChainFork.sendMapUpdated
Javadoc:
No Javadoc available
Method code:
private void sendMapUpdated(Rectangle r) {
for (int i = 0; i < mapListeners.size(); i++) {
WorldMapListener l = mapListeners.get(i);
l.tilesChanged(r);
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.MoveChainFork.splitMove
Javadoc:
No Javadoc available
Method code:
private void splitMove(Move move) {
if (move instanceof UndoMove) {
UndoMove undoneMove = (UndoMove) move;
move = undoneMove.getUndoneMove();
}
if (move instanceof CompositeMove) {
ImList<Move> moves = ((CompositeMove) move).getMoves();
for (int i = 0; i < moves.size(); i++) {
splitMove(moves.get(i));
}
} else {
for (int i = 0; i < splitMoveReceivers.size(); i++) {
MoveReceiver m = splitMoveReceivers.get(i);
m.processMove(move);
}
if (move instanceof AddItemToListMove) {
AddItemToListMove mm = (AddItemToListMove) move;
sendItemAdded(mm.getKey(), mm.getIndex(), mm.getPrincipal());
} else if (move instanceof ChangeItemInListMove) {
ChangeItemInListMove mm = (ChangeItemInListMove) move;
sendListUpdated(mm.getKey(), mm.getIndex(), mm.getPrincipal());
} else if (move instanceof RemoveItemFromListMove) {
RemoveItemFromListMove mm = (RemoveItemFromListMove) move;
sendItemRemoved(mm.getKey(), mm.getIndex(), mm.getPrincipal());
} else if (move instanceof MapUpdateMove) {
Rectangle r = ((MapUpdateMove) move).getUpdatedTiles();
sendMapUpdated(r);
} else if (move instanceof TimeTickMove) {
long currentTime = System.currentTimeMillis();
lastTickTime = currentTime;
}
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.MovePrecommitter.fromServer
Javadoc:
No Javadoc available
Method code:
void fromServer(PreMoveStatus pms) {
rollBackPrecommittedMoves();
PreMove pm = (PreMove) uncomitted.removeFirst();
if (pms.ms.ok) {
logger.finest("PreMove accepted by server: " + pms.toString());
Move m = pm.generateMove(w);
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
if (!ms.ok) {
throw new IllegalStateException();
}
} else {
logger.info("PreMove rejected by server: " + pms.ms.message);
}
precommitMoves();
}
Outgoing Methods (calls):
jfreerails.network.specifics.MovePrecommitter.precommitMoves
Javadoc:
No Javadoc available
Method code:
void precommitMoves() {
blocked = false;
while (uncomitted.size() > 0 && !blocked) {
Object first = uncomitted.getFirst();
if (first instanceof Move) {
Move m = (Move) first;
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
if (ms.ok) {
uncomitted.removeFirst();
precomitted.addLast(m);
} else {
blocked = true;
}
} else if (first instanceof PreMove) {
PreMove pm = (PreMove) first;
Move m = pm.generateMove(w);
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
if (ms.ok) {
uncomitted.removeFirst();
PreMoveAndMove pmam = new PreMoveAndMove(pm, m);
precomitted.addLast(pmam);
} else {
blocked = true;
}
}
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.MovePrecommitter.rollBackPrecommittedMoves
Javadoc:
/** * Undoes each of the precommitted moves and puts them back on the * uncommitted list. */
Method code:
/**
* Undoes each of the precommitted moves and puts them back on the
* uncommitted list.
*/
private void rollBackPrecommittedMoves() {
while (precomitted.size() > 0) {
Object last = precomitted.removeLast();
Move move2undo;
FreerailsSerializable obj2add2uncomitted;
if (last instanceof Move) {
move2undo = (Move) last;
obj2add2uncomitted = move2undo;
} else if (last instanceof PreMoveAndMove) {
PreMoveAndMove pmam = (PreMoveAndMove) last;
move2undo = pmam.m;
obj2add2uncomitted = pmam.pm;
} else {
throw new IllegalStateException();
}
MoveStatus ms = move2undo.undoMove(w, Player.AUTHORITATIVE);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
uncomitted.addFirst(obj2add2uncomitted);
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.MovePrecommitter.toServer
Javadoc:
No Javadoc available
Method code:
Move toServer(PreMove pm) {
uncomitted.addLast(pm);
precommitMoves();
if (blocked) {
return pm.generateMove(w);
}
PreMoveAndMove pmam = (PreMoveAndMove) precomitted.getLast();
return pmam.m;
}
Outgoing Methods (calls):
jfreerails.network.specifics.MovePrecommitterTest.getTime
Javadoc:
No Javadoc available
Method code:
private GameTime getTime() {
return w.currentTime();
}
Outgoing Methods (calls):
jfreerails.network.specifics.MovePrecommitterTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
w = new WorldImpl(10, 10);
committer = new MovePrecommitter(w);
}
No outgoing methods.
jfreerails.network.specifics.MovePrecommitterTest.test1
Javadoc:
/** Test simple case of precommitting then fully committing moves. */
Method code:
/** Test simple case of precommitting then fully committing moves. */
public void test1() {
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
assertFalse(oldtime.equals(newTime));
Move m = new TimeTickMove(oldtime, newTime);
MoveStatus ms = m.tryDoMove(w, Player.AUTHORITATIVE);
assertTrue(ms.ok);
committer.toServer(m);
/* The move m should now have been precommitted. */
assertEquals(newTime, getTime());
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(1, committer.precomitted.size());
committer.fromServer(ms);
/* The move m should now be full committed. */
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
assertEquals(newTime, getTime());
}
Outgoing Methods (calls):
jfreerails.network.specifics.MovePrecommitterTest.test2
Javadoc:
/** Test test clash. */
Method code:
/** Test test clash. */
public void test2() {
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
assertFalse(oldtime.equals(newTime));
Move m = new TimeTickMove(oldtime, newTime);
MoveStatus ms = m.tryDoMove(w, Player.AUTHORITATIVE);
assertTrue(ms.ok);
committer.toServer(m);
/* The move m should now have been precommitted. */
assertEquals(newTime, getTime());
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(1, committer.precomitted.size());
committer.fromServer(m);
assertFalse(m.tryDoMove(w, Player.AUTHORITATIVE).ok);
/* The move m should now be full committed. */
assertEquals(1, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
assertEquals(newTime, getTime());
committer.precommitMoves();
/*
* The committer should be block since the move on the uncommitted list
* fails to go through.
*/
assertTrue(committer.blocked);
assertEquals(1, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
Move m2 = new TimeTickMove(newTime, oldtime);
committer.fromServer(m2);
assertEquals(oldtime, getTime());
committer.fromServer(ms);
assertEquals(newTime, getTime());
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
}
Outgoing Methods (calls):
jfreerails.network.specifics.MovePrecommitterTest.test3
Javadoc:
/** Test test rejection 1. */
Method code:
/** Test test rejection 1. */
public void test3() {
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
assertFalse(oldtime.equals(newTime));
Move m = new TimeTickMove(oldtime, newTime);
MoveStatus ms = m.tryDoMove(w, Player.AUTHORITATIVE);
assertTrue(ms.ok);
committer.toServer(m);
/* The move m should now have been precommitted. */
assertEquals(newTime, getTime());
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(1, committer.precomitted.size());
/* Now, suppose the server rejected the move.. */
MoveStatus rejection = MoveStatus.moveFailed("Rejected!");
committer.fromServer(rejection);
assertEquals(oldtime, getTime());
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
}
Outgoing Methods (calls):
jfreerails.network.specifics.MovePrecommitterTest.test4
Javadoc:
/** Test test rejection 2. */
Method code:
/** Test test rejection 2. */
public void test4() {
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
assertFalse(oldtime.equals(newTime));
/* the following move should fail! */
Move m = new TimeTickMove(newTime, oldtime);
MoveStatus ms = m.tryDoMove(w, Player.AUTHORITATIVE);
assertFalse(ms.ok);
committer.toServer(m);
assertTrue(committer.blocked);
assertEquals(1, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
committer.fromServer(ms);
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
}
Outgoing Methods (calls):
jfreerails.network.specifics.MovePrecommitterTest.testPreMoves1
Javadoc:
No Javadoc available
Method code:
public void testPreMoves1() {
PreMove pm = TimeTickPreMove.INSTANCE;
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
committer.fromServer(pm);
assertEquals(newTime, getTime());
}
Outgoing Methods (calls):
jfreerails.network.specifics.MovePrecommitterTest.testPreMoves2
Javadoc:
No Javadoc available
Method code:
public void testPreMoves2() {
PreMove pm = TimeTickPreMove.INSTANCE;
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
// Send a premove to the server.
committer.toServer(pm);
assertEquals(0, committer.uncomitted.size());
assertEquals(1, committer.precomitted.size());
assertEquals(newTime, getTime());
// The server accepts it..
committer.fromServer(PreMoveStatus.PRE_MOVE_OK);
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
assertEquals(newTime, getTime());
}
Outgoing Methods (calls):
jfreerails.network.specifics.MovePrecommitterTest.testPreMoves3
Javadoc:
No Javadoc available
Method code:
public void testPreMoves3() {
PreMove pm = TimeTickPreMove.INSTANCE;
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
// Send a premove to the server.
committer.toServer(pm);
assertEquals(0, committer.uncomitted.size());
assertEquals(1, committer.precomitted.size());
assertEquals(newTime, getTime());
// The server rejects it.
committer.fromServer(PreMoveStatus.failed("failed"));
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
assertEquals(oldtime, getTime());
}
Outgoing Methods (calls):
jfreerails.network.specifics.MoveReceiver.processMove
Javadoc:
No Javadoc available
Method code:
void processMove(Move move);
No outgoing methods.
jfreerails.network.specifics.NewGameMessage2Server.execute
Javadoc:
No Javadoc available
Method code:
public MessageStatus execute(ServerControlInterface server) {
try {
server.newGame(mapName);
return new MessageStatus(id, true);
} catch (Exception e) {
return new MessageStatus(id, false, e.getMessage());
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.NewGameMessage2Server.getID
Javadoc:
No Javadoc available
Method code:
public int getID() {
return id;
}
No outgoing methods.
jfreerails.network.specifics.NewGameMessage2Server.getMapNames
Javadoc:
/** * TODO This would be better implemented in a config file, or better still * dynamically determined by scanning the directory. */
Method code:
/**
* TODO This would be better implemented in a config file, or better still
* dynamically determined by scanning the directory.
*/
public static String[] getMapNames() {
return new String[] { "South America", "Small South America" };
}
No outgoing methods.
jfreerails.network.specifics.RefreshListOfGamesMessage2Server.execute
Javadoc:
No Javadoc available
Method code:
public MessageStatus execute(ServerControlInterface server) {
server.refreshSavedGames();
return new MessageStatus(id, true);
}
Outgoing Methods (calls):
jfreerails.network.specifics.RefreshListOfGamesMessage2Server.getID
Javadoc:
No Javadoc available
Method code:
public int getID() {
return id;
}
No outgoing methods.
jfreerails.network.specifics.SaveGameMessage2Server.execute
Javadoc:
No Javadoc available
Method code:
public MessageStatus execute(ServerControlInterface server) {
try {
server.savegame(filename);
return new MessageStatus(id, true);
} catch (Exception e) {
return new MessageStatus(id, false, e.getMessage());
}
}
Outgoing Methods (calls):
jfreerails.network.specifics.SaveGameMessage2Server.getID
Javadoc:
No Javadoc available
Method code:
public int getID() {
return id;
}
No outgoing methods.
jfreerails.network.specifics.SavedGamesManager.getNewMapNames
Javadoc:
No Javadoc available
Method code:
String[] getNewMapNames();
No outgoing methods.
jfreerails.network.specifics.SavedGamesManager.getSaveGameNames
Javadoc:
No Javadoc available
Method code:
String[] getSaveGameNames();
No outgoing methods.
jfreerails.network.specifics.SavedGamesManager.loadGame
Javadoc:
No Javadoc available
Method code:
Serializable loadGame(String name) throws IOException;
No outgoing methods.
jfreerails.network.specifics.SavedGamesManager.newMap
Javadoc:
No Javadoc available
Method code:
Serializable newMap(String name) throws IOException;
No outgoing methods.
jfreerails.network.specifics.SavedGamesManager.saveGame
Javadoc:
No Javadoc available
Method code:
void saveGame(Serializable w, String s) throws IOException;
No outgoing methods.
jfreerails.network.specifics.SavedGamesManager4UnitTests.getNewMapNames
Javadoc:
No Javadoc available
Method code:
public String[] getNewMapNames() {
return mapsAvailable.clone();
}
Outgoing Methods (calls):
jfreerails.network.specifics.SavedGamesManager4UnitTests.getSaveGameNames
Javadoc:
No Javadoc available
Method code:
public String[] getSaveGameNames() {
Object[] keys = savedGames.keySet().toArray();
String[] names = new String[keys.length];
for (int i = 0; i < names.length; i++) {
names[i] = (String) keys[i];
}
return names;
}
No outgoing methods.
jfreerails.network.specifics.SavedGamesManager4UnitTests.loadGame
Javadoc:
No Javadoc available
Method code:
public Serializable loadGame(String name) throws IOException {
Serializable o = savedGames.get(name);
return Utils.cloneBySerialisation(o);
}
Outgoing Methods (calls):
jfreerails.network.specifics.SavedGamesManager4UnitTests.newMap
Javadoc:
No Javadoc available
Method code:
public Serializable newMap(String name) throws IOException {
return new WorldImpl(10, 10);
}
No outgoing methods.
jfreerails.network.specifics.SavedGamesManager4UnitTests.saveGame
Javadoc:
No Javadoc available
Method code:
public void saveGame(Serializable w, String name) throws IOException {
// Make a copy so that the saved version's state cannot be changed.
Serializable copy = Utils.cloneBySerialisation(w);
this.savedGames.put(name, copy);
}
Outgoing Methods (calls):
jfreerails.network.specifics.ServerCommandReceiver.sendCommand
Javadoc:
No Javadoc available
Method code:
void sendCommand(Message2Server c);
No outgoing methods.
jfreerails.network.specifics.ServerGameModel.getPasswords
Javadoc:
No Javadoc available
Method code:
String[] getPasswords();
No outgoing methods.
jfreerails.network.specifics.ServerGameModel.getWorld
Javadoc:
No Javadoc available
Method code:
World getWorld();
No outgoing methods.
jfreerails.network.specifics.ServerGameModel.init
Javadoc:
No Javadoc available
Method code:
void init(MoveReceiver moveExecutor);
No outgoing methods.
jfreerails.network.specifics.ServerGameModel.setWorld
Javadoc:
No Javadoc available
Method code:
void setWorld(World w, String[] passwords);
No outgoing methods.
jfreerails.network.specifics.ServerGameModel.write
Javadoc:
No Javadoc available
Method code:
void write(ObjectOutputStream objectOut) throws IOException;
No outgoing methods.
jfreerails.network.specifics.SetPropertyMessage2Client.execute
Javadoc:
No Javadoc available
Method code:
public MessageStatus execute(ClientControlInterface client) {
client.setProperty(key, value);
return new MessageStatus(id, true);
}
Outgoing Methods (calls):
jfreerails.network.specifics.SetPropertyMessage2Client.getID
Javadoc:
No Javadoc available
Method code:
public int getID() {
return id;
}
No outgoing methods.
jfreerails.network.specifics.SetWorldMessage2Client.execute
Javadoc:
No Javadoc available
Method code:
public MessageStatus execute(ClientControlInterface client) {
client.setGameModel(world.defensiveCopy());
return new MessageStatus(id, true);
}
Outgoing Methods (calls):
jfreerails.network.specifics.SetWorldMessage2Client.getID
Javadoc:
No Javadoc available
Method code:
public int getID() {
return id;
}
No outgoing methods.
jfreerails.network.specifics.SimpleServerGameModel.getPasswords
Javadoc:
No Javadoc available
Method code:
public String[] getPasswords() {
return passwords.clone();
}
Outgoing Methods (calls):
jfreerails.network.specifics.SimpleServerGameModel.getWorld
Javadoc:
No Javadoc available
Method code:
public World getWorld() {
return w;
}
No outgoing methods.
jfreerails.network.specifics.SimpleServerGameModel.init
Javadoc:
No Javadoc available
Method code:
public void init(MoveReceiver moveExecuter) {
}
No outgoing methods.
jfreerails.network.specifics.SimpleServerGameModel.itemAdded
Javadoc:
No Javadoc available
Method code:
public void itemAdded(KEY key, int index, FreerailsPrincipal principal) {
}
No outgoing methods.
jfreerails.network.specifics.SimpleServerGameModel.itemRemoved
Javadoc:
No Javadoc available
Method code:
public void itemRemoved(KEY key, int index, FreerailsPrincipal principal) {
}
No outgoing methods.
jfreerails.network.specifics.SimpleServerGameModel.listUpdated
Javadoc:
/** * Notifies that a list has been updated, providing details about the change. * This method is called when a list item is modified, specifying the key of the * updated item, its index in the list, and the principal (user context) associated * with the update. The principal is used to validate access or determine user-specific * behavior. * * @param key The unique identifier of the list item that was updated. * @param index The position of the updated item within the list. * @param principal The user principal associated with the update, used for access control. */
Method code:
public void listUpdated(KEY key, int index, FreerailsPrincipal principal) {
}
No outgoing methods.
jfreerails.network.specifics.SimpleServerGameModel.setWorld
Javadoc:
No Javadoc available
Method code:
public void setWorld(World w, String[] passwords) {
this.w = w;
this.passwords = passwords.clone();
}
Outgoing Methods (calls):
jfreerails.network.specifics.SimpleServerGameModel.update
Javadoc:
No Javadoc available
Method code:
public void update() {
}
No outgoing methods.
jfreerails.network.specifics.SimpleServerGameModel.write
Javadoc:
No Javadoc available
Method code:
public void write(ObjectOutputStream objectOut) throws IOException {
}
No outgoing methods.
jfreerails.network.specifics.UntriedMoveReceiver.processPreMove
Javadoc:
No Javadoc available
Method code:
void processPreMove(PreMove pm);
No outgoing methods.
jfreerails.network.specifics.UntriedMoveReceiver.tryDoMove
Javadoc:
No Javadoc available
Method code:
MoveStatus tryDoMove(Move move);
No outgoing methods.
jfreerails.server.CalcSupplyAtStations.doProcessing
Javadoc:
/** * * Loop through each known station, call calculations method. * */
Method code:
/**
*
* Loop through each known station, call calculations method.
*
*/
public void doProcessing() {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
NonNullElements iterator = new NonNullElements(KEY.STATIONS, w,
principal);
while (iterator.next()) {
StationModel stationBefore = (StationModel) iterator
.getElement();
CalcCargoSupplyRateAtStation supplyRate;
supplyRate = new CalcCargoSupplyRateAtStation(w,
stationBefore.x, stationBefore.y);
StationModel stationAfter = supplyRate
.calculations(stationBefore);
if (!stationAfter.equals(stationBefore)) {
Move move = new ChangeStationMove(iterator.getIndex(),
stationBefore, stationAfter, principal);
this.moveReceiver.processMove(move);
}
}
}
}
Outgoing Methods (calls):
jfreerails.server.CargoAtStationsGenerator.calculateAmountToAdd
Javadoc:
No Javadoc available
Method code:
int calculateAmountToAdd(int amountSuppliedPerYear, int month) {
// Note, jan is month 0.
int totalAtMonthEnd = amountSuppliedPerYear * (month + 1) / 12;
int totalAtMonthStart = amountSuppliedPerYear * (month) / 12;
int amount = totalAtMonthEnd - totalAtMonthStart;
return amount;
}
No outgoing methods.
jfreerails.server.CargoAtStationsGenerator.update
Javadoc:
/** Call this method once a month. */
Method code:
/** Call this method once a month. */
public void update(World w, MoveReceiver moveReceiver) {
for (int k = 0; k < w.getNumberOfPlayers(); k++) {
FreerailsPrincipal principal = w.getPlayer(k).getPrincipal();
NonNullElements nonNullStations = new NonNullElements(KEY.STATIONS,
w, principal);
while (nonNullStations.next()) {
StationModel station = (StationModel) nonNullStations
.getElement();
SupplyAtStation supply = station.getSupply();
ImmutableCargoBundle cargoBundle = (ImmutableCargoBundle) w
.get(principal, KEY.CARGO_BUNDLES,
station.getCargoBundleID());
MutableCargoBundle before = new MutableCargoBundle(cargoBundle);
MutableCargoBundle after = new MutableCargoBundle(cargoBundle);
int stationNumber = nonNullStations.getIndex();
/*
* Get the iterator from a copy to avoid a
* ConcurrentModificationException if the amount gets set to
* zero and the CargoBatch removed from the cargo bundle. LL
*/
Iterator<CargoBatch> it = after.toImmutableCargoBundle()
.cargoBatchIterator();
while (it.hasNext()) {
CargoBatch cb = it.next();
int amount = after.getAmount(cb);
if (amount > 0) {
// (23/24)^12 = 0.60
after.setAmount(cb, amount * 23 / 24);
}
}
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
int amountSupplied = supply.getSupply(i);
if (amountSupplied > 0) {
CargoBatch cb = new CargoBatch(i, station.x, station.y,
0, stationNumber);
int amountAlready = after.getAmount(cb);
// Obtain the month
GameTime time = w.currentTime();
GameCalendar calendar = (GameCalendar) w
.get(ITEM.CALENDAR);
int month = calendar.getMonth(time.getTicks());
int amountAfter = calculateAmountToAdd(amountSupplied,
month)
+ amountAlready;
after.setAmount(cb, amountAfter);
}
}
Move m = new ChangeCargoBundleMove(before
.toImmutableCargoBundle(), after
.toImmutableCargoBundle(), station.getCargoBundleID(),
principal);
moveReceiver.processMove(m);
}
}
}
Outgoing Methods (calls):
jfreerails.server.CargoAtStationsGeneratorTest.assertCorrectTotalAddedOverYear
Javadoc:
/** * If, say, 14 units get added each year, some month we should add 1 and * others we should add 2 such that over the year exactly 14 units get * added. */
Method code:
/**
* If, say, 14 units get added each year, some month we should add 1 and
* others we should add 2 such that over the year exactly 14 units get
* added.
*/
private void assertCorrectTotalAddedOverYear(final int unitPerYear) {
CargoAtStationsGenerator cargoGenerator = new CargoAtStationsGenerator();
int amountAddedThisSoFar = 0;
for (int i = 0; i < 12; i++) {
amountAddedThisSoFar += cargoGenerator.calculateAmountToAdd(
unitPerYear, i);
}
assertEquals(unitPerYear, amountAddedThisSoFar);
}
Outgoing Methods (calls):
jfreerails.server.CargoAtStationsGeneratorTest.testCalculateAmountToAdd
Javadoc:
No Javadoc available
Method code:
public void testCalculateAmountToAdd() {
CargoAtStationsGenerator cargoGenerator = new CargoAtStationsGenerator();
int amount = cargoGenerator.calculateAmountToAdd(12, 0);
assertEquals(1, amount);
assertCorrectTotalAddedOverYear(0);
assertCorrectTotalAddedOverYear(12);
assertCorrectTotalAddedOverYear(14);
assertCorrectTotalAddedOverYear(140);
assertCorrectTotalAddedOverYear(3);
}
Outgoing Methods (calls):
jfreerails.server.CityEconomicModel.addTile
Javadoc:
No Javadoc available
Method code:
void addTile(TerrainType type) {
Random rand = new Random();
// Pick a spot at random at which to place the tile.
if (clearTiles.size() > 0) {
int tilePos = rand.nextInt(clearTiles.size());
Point p = clearTiles.remove(tilePos);
if (type.getCategory().equals(TerrainType.Category.Urban)) {
urbanTiles.add(new Tile(p, type));
} else if (type.getCategory().equals(TerrainType.Category.Industry)) {
industryTiles.add(new Tile(p, type));
industriesNotAtCity.remove(type);
} else if (type.getCategory().equals(TerrainType.Category.Country)) {
throw new IllegalArgumentException(
"call remove(.) to replace a city tile with a country tile!");
} else if (type.getCategory().equals(TerrainType.Category.Resource)) {
resourceTiles.add(new Tile(p, type));
}
}
}
Outgoing Methods (calls):
jfreerails.server.CityEconomicModel.loadFromMap
Javadoc:
No Javadoc available
Method code:
void loadFromMap(ReadOnlyWorld w, int cityID) {
/* Reset lists of tiles. */
urbanTiles.clear();
industryTiles.clear();
clearTiles.clear();
resourceTiles.clear();
/* Set up the list of industries not at the city. */
industriesNotAtCity.clear();
for (int i = 0; i < w.size(SKEY.TERRAIN_TYPES); i++) {
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
if (type.getCategory().equals(TerrainType.Category.Industry)) {
industriesNotAtCity.add(type);
}
}
stations = 0;
/* Identify city's bounds. */
Rectangle mapRect = new Rectangle(0, 0, w.getMapWidth(), w
.getMapHeight());
CityModel city = (CityModel) w.get(SKEY.CITIES, cityID);
Rectangle cityArea = new Rectangle(city.getCityX() - 3,
city.getCityY() - 3, 7, 7);
cityArea = cityArea.intersection(mapRect);
/* Count tile types. */
for (int x = cityArea.x; x < cityArea.x + cityArea.width; x++) {
for (int y = cityArea.y; y < cityArea.y + cityArea.height; y++) {
FreerailsTile tile = (FreerailsTile) w.getTile(x, y);
/* Count the number of stations at the city. */
if (tile.getTrackPiece().getTrackRule().isStation()) {
stations++;
}
int terrainTypeNumber = tile.getTerrainTypeID();
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES,
terrainTypeNumber);
if (type.getCategory().equals(TerrainType.Category.Urban)) {
urbanTiles.add(new Tile(new Point(x, y), type));
} else if (type.getCategory().equals(
TerrainType.Category.Industry)) {
industryTiles.add(new Tile(new Point(x, y), type));
industriesNotAtCity.remove(type);
} else if (type.getCategory().equals(
TerrainType.Category.Country)) {
clearTiles.add(new Point(x, y));
} else if (type.getCategory().equals(
TerrainType.Category.Resource)) {
resourceTiles.add(new Tile(new Point(x, y), type));
}
}
}
}
Outgoing Methods (calls):
jfreerails.server.CityEconomicModel.size
Javadoc:
No Javadoc available
Method code:
int size() {
return this.urbanTiles.size() + this.industryTiles.size()
+ this.resourceTiles.size();
}
No outgoing methods.
jfreerails.server.CityEconomicModel.write2map
Javadoc:
No Javadoc available
Method code:
void write2map(World w) {
for (int i = 0; i < urbanTiles.size(); i++) {
writeTile(w, urbanTiles.get(i));
}
for (int i = 0; i < industryTiles.size(); i++) {
writeTile(w, industryTiles.get(i));
}
for (int i = 0; i < resourceTiles.size(); i++) {
writeTile(w, resourceTiles.get(i));
}
}
Outgoing Methods (calls):
jfreerails.server.CityEconomicModel.writeTile
Javadoc:
No Javadoc available
Method code:
private void writeTile(World w, Tile tile) {
int type = 0;
while (!w.get(SKEY.TERRAIN_TYPES, type).equals(tile.type)) {
type++;
}
int x = tile.p.x;
int y = tile.p.y;
FreerailsTile fTile = (FreerailsTile) w.getTile(x, y);
fTile = FreerailsTile.getInstance(type, fTile.getTrackPiece());
w.setTile(x, y, fTile);
}
Outgoing Methods (calls):
jfreerails.server.CityEconomicModelTest.testLoadFromMap
Javadoc:
/** * Tests generating populated CityEconomicModel from cities on the map. */
Method code:
/**
* Tests generating populated CityEconomicModel from cities on the map.
*/
public void testLoadFromMap() {
World w = MapFixtureFactory.getWorld(100, 100);
CityModel newYork = new CityModel("New York", 10, 20);
w.add(SKEY.CITIES, newYork);
CityEconomicModel city = new CityEconomicModel();
city.loadFromMap(w, 0);
assertEquals(0, city.industryTiles.size());
assertEquals(0, city.urbanTiles.size());
assertEquals("A city is a 7*7 area", 49, city.clearTiles.size());
}
Outgoing Methods (calls):
jfreerails.server.CityEconomicModelTest.testUtilityCalculation
Javadoc:
/** Tests calculating the utility of a City. */
Method code:
/** Tests calculating the utility of a City. */
public void testUtilityCalculation() {
}
No outgoing methods.
jfreerails.server.CitySAXParser.endDocument
Javadoc:
No Javadoc available
Method code:
@Override
public void endDocument() throws SAXException {
for (int i = 0; i < cities.size(); i++) {
CityModel tempCity = cities.elementAt(i);
world.add(SKEY.CITIES, new CityModel(tempCity.getCityName(),
tempCity.getCityX(), tempCity.getCityY()));
}
}
Outgoing Methods (calls):
jfreerails.server.CitySAXParser.startElement
Javadoc:
No Javadoc available
Method code:
@Override
public void startElement(String namespaceURI, String sName, String qName,
Attributes attrs) throws SAXException {
String cityName = null;
int x = 0;
int y = 0;
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String aName = attrs.getLocalName(i); // Attr name
if (aName.equals("")) {
aName = attrs.getQName(i);
}
// put values in CityModel obj
if (aName.equals("name")) {
cityName = attrs.getValue(i);
}
if (aName.equals("x")) {
x = Integer.parseInt(attrs.getValue(i));
}
if (aName.equals("y")) {
y = Integer.parseInt(attrs.getValue(i));
CityModel city = new CityModel(cityName, x, y);
cities.addElement(city);
}
}
// end for loop
}
// end if
}
No outgoing methods.
jfreerails.server.CityTilePositioner.addIndustryTile
Javadoc:
No Javadoc available
Method code:
private void addIndustryTile(CityEconomicModel city) {
int size = city.industriesNotAtCity.size();
if (size > 0) {
int tileTypeNo = random.nextInt(size);
TerrainType type = city.industriesNotAtCity.get(tileTypeNo);
city.addTile(type);
}
}
Outgoing Methods (calls):
jfreerails.server.CityTilePositioner.addResourceTile
Javadoc:
No Javadoc available
Method code:
private void addResourceTile(CityEconomicModel city) {
int tileTypeNo = random.nextInt(resourceTerrainTypes.size());
TerrainType type = resourceTerrainTypes.get(tileTypeNo);
city.addTile(type);
}
Outgoing Methods (calls):
jfreerails.server.CityTilePositioner.addUrbanTile
Javadoc:
No Javadoc available
Method code:
private void addUrbanTile(CityEconomicModel city) {
int tileTypeNo = random.nextInt(urbanTerrainTypes.size());
TerrainType type = urbanTerrainTypes.get(tileTypeNo);
city.addTile(type);
}
Outgoing Methods (calls):
jfreerails.server.CityTilePositioner.growCities
Javadoc:
No Javadoc available
Method code:
void growCities() {
final int numCities = w.size(SKEY.CITIES);
/*
* At some stage this will be refined to take into account how much
* cargo has been picked up and delivered and what city tiles are
* already present.
*/
for (int cityId = 0; cityId < numCities; cityId++) {
CityEconomicModel city = new CityEconomicModel();
city.loadFromMap(w, cityId);
// Only increase cities with stations and less than 16 tiles
if (city.size() < 16 && city.stations > 0) {
switch (random.nextInt(10)) {
case 0:
case 1:
addResourceTile(city); // 20% chance
break;
case 2:
case 3:
case 4:
case 5:
addUrbanTile(city); // 40% chance
break;
case 6:
addIndustryTile(city); // 10% chance
break;
default:
// do nothing, 30% chance
break;
}
city.write2map(w);
}
}
}
Outgoing Methods (calls):
jfreerails.server.CityTilePositioner.initCities
Javadoc:
No Javadoc available
Method code:
void initCities() {
final int numCities = w.size(SKEY.CITIES);
CityEconomicModel[] cities = new CityEconomicModel[numCities];
for (int cityId = 0; cityId < numCities; cityId++) {
CityEconomicModel city = new CityEconomicModel();
city.loadFromMap(w, cityId);
final int urbanTiles = 2 + random.nextInt(3);
for (int i = 0; i < urbanTiles; i++) {
addUrbanTile(city);
}
final int industryTiles = random.nextInt(3);
for (int i = 0; i < industryTiles; i++) {
addIndustryTile(city);
}
final int resourceTiles = random.nextInt(3);
for (int i = 0; i < resourceTiles; i++) {
addResourceTile(city);
}
city.write2map(w);
cities[cityId] = city;
}
}
Outgoing Methods (calls):
jfreerails.server.InputCityNames.readCityNames
Javadoc:
No Javadoc available
Method code:
public static void readCityNames(World w, URL filename) throws SAXException {
InputSource is = new InputSource(filename.toString());
DefaultHandler handler = new CitySAXParser(w);
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(is, handler);
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
}
}
No outgoing methods.
jfreerails.server.InterestChargeMoveGenerator.generateMove
Javadoc:
No Javadoc available
Method code:
private static AddTransactionMove generateMove(World w,
FreerailsPrincipal principal) {
long interestDue = 0;
for (int i = 0; i < w.getNumberOfTransactions(principal); i++) {
Transaction t = w.getTransaction(principal, i);
if (t instanceof BondTransaction) {
BondTransaction bt = (BondTransaction) t;
int interestRate = bt.getType();
long bondAmount = BondTransaction.BOND_VALUE_ISSUE.getAmount();
interestDue += (interestRate * bondAmount / 100)
* bt.getQuantity();
}
}
Transaction t = new Bill(new Money(interestDue),
Transaction.Category.INTEREST_CHARGE);
return new AddTransactionMove(principal, t);
}
Outgoing Methods (calls):
jfreerails.server.InterestChargeMoveGenerator.update
Javadoc:
No Javadoc available
Method code:
public void update(World w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
Move m = generateMove(w, principal);
moveReceiver.processMove(m);
}
}
Outgoing Methods (calls):
jfreerails.server.MapCustomizer.buildStation
Javadoc:
No Javadoc available
Method code:
public MapCustomizer buildStation(ImPoint a) {
MoveStatus ms = stationBuilder.buildStation(a);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
return this;
}
Outgoing Methods (calls):
jfreerails.server.MapCustomizer.buildTrack
Javadoc:
No Javadoc available
Method code:
public MapCustomizer buildTrack(ImPoint a, ImPoint b) throws PathNotFoundException {
pathFinder.setupSearch(a, b, bts);
pathFinder.search(-1);
List<ImPoint> pathAsPoints = pathFinder.pathAsPoints();
ImPoint from = a;
for (int i = 0; i < pathAsPoints.size(); i++) {
ImPoint to = pathAsPoints.get(i);
Step vector = Step.getInstance(to.x - from.x, to.y
- from.y);
FreerailsTile tile = (FreerailsTile) w.getTile(
from.x, from.y);
if (!tile.getTrackPiece().getTrackConfiguration().contains(vector)) {
producer.buildTrack(from, vector);
}
from = to;
}
return this;
}
Outgoing Methods (calls):
jfreerails.server.MapCustomizer.buildTrain
Javadoc:
No Javadoc available
Method code:
public MapCustomizer buildTrain(ImPoint a, int... stops) {
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
MutableSchedule s = new MutableSchedule();
for (int stop : stops) {
s.addOrder(new TrainOrdersModel(stop, null, false, true));
}
ImmutableSchedule defaultSchedule = s.toImmutableSchedule();
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(),
a, principal, defaultSchedule);
Move m = preMove.generateMove(w);
MoveStatus status = m.doMove(w, Player.AUTHORITATIVE);
if (!status.ok) {
throw new IllegalStateException(status.message);
}
return this;
}
Outgoing Methods (calls):
jfreerails.server.MapCustomizer.getStationId
Javadoc:
/** * Returns -1 if no station here or the id of the station if one is * present. */
Method code:
/**
* Returns -1 if no station here or the id of the station if one is
* present.
*/
public int getStationId(ImPoint location) {
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
FreerailsTile tile = (FreerailsTile) w.getTile(location.x, location.y);
TrackRule trackRule = tile.getTrackPiece().getTrackRule();
if (trackRule.isStation()
&& tile.getTrackPiece().getOwnerID() == w.getID(principal)) {
for (int i = 0; i < w.size(principal, KEY.STATIONS); i++) {
StationModel station = (StationModel) w.get(principal,
KEY.STATIONS, i);
if (null != station && station.getLocation().equals(location)) {
return i;
}
}
throw new IllegalStateException();
} else {
return -1;
}
}
Outgoing Methods (calls):
jfreerails.server.MapFactory.setTile
Javadoc:
No Javadoc available
Method code:
private static void setTile(int x, int y, FreerailsTile tile) {
if (!non_countryTypes.contains(new Integer(((FreerailsTile) world
.getTile(x, y)).getTerrainTypeID()))) {
world.setTile(x, y, tile);
}
}
Outgoing Methods (calls):
jfreerails.server.MapFactory.setupMap
Javadoc:
No Javadoc available
Method code:
public static void setupMap(URL map_url, WorldImpl w,
FreerailsProgressMonitor pm) {
// Setup progress monitor..
pm.setValue(0);
world = w;
Image mapImage = (new ImageIcon(map_url)).getImage();
Rectangle mapRect = new java.awt.Rectangle(0, 0, mapImage
.getWidth(null), mapImage.getHeight(null));
BufferedImage mapBufferedImage = new BufferedImage(mapRect.width,
mapRect.height, BufferedImage.TYPE_INT_ARGB);
Graphics g = mapBufferedImage.getGraphics();
g.drawImage(mapImage, 0, 0, null);
w.setupMap(mapRect.width, mapRect.height);
pm.nextStep(mapRect.width);
HashMap<Integer, Integer> rgb2TerrainType = new HashMap<Integer, Integer>();
for (int i = 0; i < w.size(SKEY.TERRAIN_TYPES); i++) {
TerrainType tilemodel = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
rgb2TerrainType.put(tilemodel.getRGB(), i);
}
TerrainType terrainTypeTile;
for (int c = 0; c < w.size(SKEY.TERRAIN_TYPES); c++) {
terrainTypeTile = (TerrainType) w.get(SKEY.TERRAIN_TYPES, c);
if (terrainTypeTile.getCategory().equals(
TerrainType.Category.Country)) {
if ((!terrainTypeTile.getTerrainTypeName().equals("Clear"))) {
countryTypes.add(new Integer(c));
}
}
if (terrainTypeTile.getCategory()
.equals(TerrainType.Category.Ocean)
|| terrainTypeTile.getCategory().equals(
TerrainType.Category.River)
|| terrainTypeTile.getCategory().equals(
TerrainType.Category.Hill)) {
non_countryTypes.add(new Integer(c));
}
}
TerrainRandomiser terrainRandomiser = new TerrainRandomiser(
countryTypes, non_countryTypes);
/*
* create vector to keep track of terrain randomisation 'clumping'
*/
Vector<RandomTerrainValue> locations = new Vector<RandomTerrainValue>();
for (int x = 0; x < mapRect.width; x++) {
pm.setValue(x);
for (int y = 0; y < mapRect.height; y++) {
int rgb = mapBufferedImage.getRGB(x, y);
FreerailsTile tile;
Integer type = rgb2TerrainType.get(rgb);
if (null == type) {
throw new NullPointerException(
"There is no terrain type mapped to rgb value "
+ rgb + " at location " + x + ", " + y);
}
tile = FreerailsTile.getInstance(terrainRandomiser
.getNewType(type.intValue()));
if (countryTypes.contains(tile.getTerrainTypeID())) {
locations.add(new RandomTerrainValue(x, y, tile
.getTerrainTypeID()));
}
w.setTile(x, y, tile);
}
}
for (int i = 0; i < locations.size(); i++) {
RandomTerrainValue rtv = locations.elementAt(i);
FreerailsTile tile = FreerailsTile.getInstance(rtv.getType());
int x = rtv.getX();
int y = rtv.getY();
int val = 3;
double prob = 0.75;
if (w.boundsContain(x - val, y - val)
&& w.boundsContain(x + val, y + val)) {
for (int m = x - val; m < x + val; m++) {
for (int n = y - val; n < y + val; n++) {
if (Math.random() > prob) {
setTile(m, n, tile);
}
}
}
}
}
}
Outgoing Methods (calls):
jfreerails.server.MapFixtureFactory2.generateWorld
Javadoc:
No Javadoc available
Method code:
private static World generateWorld() {
World world = new WorldImpl(50, 50);
TileSetFactory tileFactory = new TileSetFactoryImpl();
WagonAndEngineTypesFactory wetf = new WagonAndEngineTypesFactory();
wetf.addTypesToWorld(world);
tileFactory.addTerrainTileTypesList(world);
URL track_xml_url = OldWorldImpl.class
.getResource("/jfreerails/data/track_tiles.xml");
Track_TilesHandlerImpl trackSetFactory = new Track_TilesHandlerImpl(
track_xml_url);
trackSetFactory.addTrackRules(world);
// Add 4 players
for (int i = 0; i < 4; i++) {
String name = "player" + i;
Player p = new Player(name, i);
AddPlayerMove move = AddPlayerMove.generateMove(world, p);
MoveStatus ms = move.doMove(world, Player.AUTHORITATIVE);
assert(ms.ok);
}
world.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
world.setTime(new GameTime(0));
world.set(ITEM.GAME_SPEED, new GameSpeed(10));
world.set(ITEM.GAME_RULES, GameRules.DEFAULT_RULES);
int clearTypeID = 0;
// Fill the world with clear terrain.
for (int i = 0; i < world.size(SKEY.TERRAIN_TYPES); i++) {
TerrainType tt = (TerrainType) world.get(SKEY.TERRAIN_TYPES, i);
if ("Clear".equals(tt.getTerrainTypeName())) {
clearTypeID = i;
break;
}
}
FreerailsTile tile = FreerailsTile.getInstance(clearTypeID);
for (int x = 0; x < world.getMapWidth(); x++) {
for (int y = 0; y < world.getMapHeight(); y++) {
world.setTile(x, y, tile);
}
}
return world;
}
Outgoing Methods (calls):
jfreerails.server.MapFixtureFactory2.getCopy
Javadoc:
/** * Returns a world object with a map of size 50*50, 4 players, and track, * terrain and cargo types as specified in the xml files used by the actual * game. */
Method code:
/**
* Returns a world object with a map of size 50*50, 4 players, and track,
* terrain and cargo types as specified in the xml files used by the actual
* game.
*/
synchronized public static World getCopy() {
if (null == w) {
w = generateWorld();
}
return w.defensiveCopy();
}
Outgoing Methods (calls):
jfreerails.server.MapFixtureFactory2Test.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
// TODO Auto-generated method stub
super.setUp();
w1 = getCopy();
}
Outgoing Methods (calls):
jfreerails.server.MapFixtureFactory2Test.testGetCopy
Javadoc:
No Javadoc available
Method code:
public void testGetCopy() {
World w2;
w1 = getCopy();
assertNotNull(w1);
w2 = getCopy();
assertNotNull(w2);
assertNotSame(w1, w2);
assertEquals(w1, w2);
}
Outgoing Methods (calls):
jfreerails.server.MapFixtureFactory2Test.testLists
Javadoc:
No Javadoc available
Method code:
public void testLists() {
assertTrue(w1.size(SKEY.CARGO_TYPES) > 0);
assertTrue(w1.size(SKEY.TRACK_RULES) > 0);
assertTrue(w1.size(SKEY.TERRAIN_TYPES) > 0);
}
Outgoing Methods (calls):
jfreerails.server.MapFixtureFactory2Test.testMap
Javadoc:
No Javadoc available
Method code:
public void testMap() {
assertEquals(w1.getMapWidth(), 50);
assertEquals(w1.getMapWidth(), 50);
}
Outgoing Methods (calls):
jfreerails.server.MapFixtureFactory2Test.testPlayers
Javadoc:
No Javadoc available
Method code:
public void testPlayers() {
assertEquals(4, w1.getNumberOfPlayers());
}
Outgoing Methods (calls):
jfreerails.server.MapFixtureFactory2Test.testThatStockIsIssued
Javadoc:
No Javadoc available
Method code:
public void testThatStockIsIssued(){
FreerailsPrincipal p = w1.getPlayer(0).getPrincipal();
int stock = 0;
Money cash = w1.getCurrentBalance(p);
assertEquals(new Money(1000000), cash);
int numberOfTransactions = w1.getNumberOfTransactions(p);
assertTrue(numberOfTransactions > 0);
for(int i = 0; i < numberOfTransactions; i++){
Transaction t = w1.getTransaction(p, i);
if(t.getCategory().equals(Transaction.Category.ISSUE_STOCK)){
AddItemTransaction ait = (AddItemTransaction)t;
stock += ait.getQuantity();
}
}
assertEquals(100000, stock);
}
Outgoing Methods (calls):
jfreerails.server.OldWorldImpl.createWorldFromMapFile
Javadoc:
/** Note, the map name is converted to lower case and any spaces * are replaced with underscores. * */
Method code:
/** Note, the map name is converted to lower case and any spaces
* are replaced with underscores.
*
*/
public static World createWorldFromMapFile(String mapName,
FreerailsProgressMonitor pm) {
mapName = mapName.toLowerCase();
mapName = mapName.replace(' ', '_');
pm.setValue(0);
pm.nextStep(7);
int progress = 0;
TileSetFactory tileFactory = new TileSetFactoryImpl();
pm.setValue(++progress);
WorldImpl w = new WorldImpl();
pm.setValue(++progress);
WagonAndEngineTypesFactory wetf = new WagonAndEngineTypesFactory();
pm.setValue(++progress);
wetf.addTypesToWorld(w);
pm.setValue(++progress);
tileFactory.addTerrainTileTypesList(w);
pm.setValue(++progress);
URL track_xml_url = OldWorldImpl.class
.getResource("/jfreerails/data/track_tiles.xml");
Track_TilesHandlerImpl trackSetFactory = new Track_TilesHandlerImpl(
track_xml_url);
pm.setValue(++progress);
trackSetFactory.addTrackRules(w);
pm.setValue(++progress);
// Load the terrain map
URL map_url = OldWorldImpl.class.getResource("/jfreerails/data/"
+ mapName + ".png");
MapFactory.setupMap(map_url, w, pm);
// Load the city names
URL cities_xml_url = OldWorldImpl.class.getResource("/jfreerails/data/"
+ mapName + "_cities.xml");
try {
InputCityNames.readCityNames(w, cities_xml_url);
} catch (SAXException e) {
}
// Randomly position the city tiles
CityTilePositioner ctp = new CityTilePositioner(w);
ctp.initCities();
// Set the time..
w.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
w.setTime(new GameTime(0));
w.set(ITEM.GAME_SPEED, new GameSpeed(10));
w.set(ITEM.GAME_RULES, GameRules.DEFAULT_RULES);
/*
* Note, money used to get added to player accounts here, now it is done
* when players are added. See AddPlayerMove
*/
return w;
}
Outgoing Methods (calls):
jfreerails.server.RandomTerrainValue.getType
Javadoc:
No Javadoc available
Method code:
public int getType() {
return terrainType;
}
No outgoing methods.
jfreerails.server.RandomTerrainValue.getX
Javadoc:
No Javadoc available
Method code:
public int getX() {
return x;
}
No outgoing methods.
jfreerails.server.RandomTerrainValue.getY
Javadoc:
No Javadoc available
Method code:
public int getY() {
return y;
}
No outgoing methods.
jfreerails.server.SavFileFilter.accept
Javadoc:
No Javadoc available
Method code:
public boolean accept(File dir, String name) {
return (name.endsWith(".sav"));
}
No outgoing methods.
jfreerails.server.SavedGamesManagerImpl.getNewMapNames
Javadoc:
No Javadoc available
Method code:
public String[] getNewMapNames() {
return NewGameMessage2Server.getMapNames();
}
Outgoing Methods (calls):
jfreerails.server.SavedGamesManagerImpl.getSaveGameNames
Javadoc:
No Javadoc available
Method code:
public String[] getSaveGameNames() {
java.io.File dir = new File("./");
FilenameFilter filter = new SavFileFilter();
String[] files = dir.list(filter);
return files;
}
No outgoing methods.
jfreerails.server.SavedGamesManagerImpl.loadGame
Javadoc:
No Javadoc available
Method code:
public Serializable loadGame(String name) throws IOException {
long startTime = System.currentTimeMillis();
logger.info("Loading game.. " + name);
FileInputStream in = new FileInputStream(name);
GZIPInputStream zipin = new GZIPInputStream(in);
ObjectInputStream objectIn = new ObjectInputStream(zipin);
String version_string;
try {
version_string = (String) objectIn.readObject();
if (!ServerControlInterface.VERSION.equals(version_string)) {
throw new IOException(version_string);
}
Serializable game = (Serializable) objectIn.readObject();
/**
* load player private data
*/
// for (int i = 0; i < world.getNumberOfPlayers(); i++) {
// Player player = world.getPlayer(i);
// player.loadSession(objectIn);
// }
long finishTime = System.currentTimeMillis();
long deltaTime = finishTime - startTime;
logger.info("done, " + deltaTime + "ms");
return game;
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IOException(e.getMessage());
} catch (InvalidClassException e) {
// e.printStackTrace();
throw new IOException(e.getMessage());
}
}
No outgoing methods.
jfreerails.server.SavedGamesManagerImpl.newMap
Javadoc:
No Javadoc available
Method code:
public Serializable newMap(String name) throws IOException {
return OldWorldImpl.createWorldFromMapFile(name,
FreerailsProgressMonitor.NULL_INSTANCE);
}
Outgoing Methods (calls):
jfreerails.server.SavedGamesManagerImpl.saveGame
Javadoc:
No Javadoc available
Method code:
public void saveGame(Serializable w, String s) throws IOException {
long startTime = System.currentTimeMillis();
logger.info("Saving game.. " + s);
FileOutputStream out = new FileOutputStream(s);
GZIPOutputStream zipout = new GZIPOutputStream(out);
ObjectOutputStream objectOut = new ObjectOutputStream(zipout);
objectOut.writeObject(ServerControlInterface.VERSION);
objectOut.writeObject(w);
objectOut.flush();
objectOut.close();
out.close();
long finishTime = System.currentTimeMillis();
long deltaTime = finishTime - startTime;
logger.info("done, " + deltaTime + "ms");
}
No outgoing methods.
jfreerails.server.ServerAutomaton.initAutomaton
Javadoc:
/** * Initializes the automaton with a connection to the MoveExecutor. */
Method code:
/**
* Initializes the automaton with a connection to the MoveExecutor.
*/
public void initAutomaton(MoveReceiver mr);
No outgoing methods.
jfreerails.server.ServerGameModelImpl.getPasswords
Javadoc:
No Javadoc available
Method code:
public String[] getPasswords() {
return passwords.clone();
}
Outgoing Methods (calls):
jfreerails.server.ServerGameModelImpl.getWorld
Javadoc:
No Javadoc available
Method code:
public World getWorld() {
return world;
}
No outgoing methods.
jfreerails.server.ServerGameModelImpl.init
Javadoc:
No Javadoc available
Method code:
public void init(MoveReceiver newMoveExecuter) {
this.moveExecuter = newMoveExecuter;
tb = new TrainUpdater(newMoveExecuter);
calcSupplyAtStations = new CalcSupplyAtStations(world, newMoveExecuter);
for (int i = 0; i < serverAutomata.size(); i++) {
serverAutomata.get(i).initAutomaton(newMoveExecuter);
}
tb.initAutomaton(newMoveExecuter);
nextModelUpdateDue = System.currentTimeMillis();
}
Outgoing Methods (calls):
jfreerails.server.ServerGameModelImpl.monthEnd
Javadoc:
/** This is called at the start of each new month. */
Method code:
/** This is called at the start of each new month. */
private void monthEnd() {
calcSupplyAtStations.doProcessing();
CargoAtStationsGenerator cargoAtStationsGenerator = new CargoAtStationsGenerator();
cargoAtStationsGenerator.update(world, moveExecuter);
}
Outgoing Methods (calls):
jfreerails.server.ServerGameModelImpl.setWorld
Javadoc:
No Javadoc available
Method code:
public void setWorld(World w, String[] passwords) {
this.world = w;
this.serverAutomata.clear();
this.passwords = passwords.clone();
}
Outgoing Methods (calls):
jfreerails.server.ServerGameModelImpl.update
Javadoc:
/** * */
Method code:
/**
*
*/
public synchronized void update() {
long frameStartTime = System.currentTimeMillis();
while (nextModelUpdateDue <= frameStartTime) {
/*
* First do the things that need doing whether or not the game is
* paused.
*/
tb.buildTrains(world);
int gameSpeed = ((GameSpeed) world.get(ITEM.GAME_SPEED)).getSpeed();
if (gameSpeed > 0) {
/*
* Update the time first, since other updates might need to know
* the current time.
*/
updateGameTime();
// now do the other updates
tb.moveTrains(world);
// Check whether we are about to start a new year..
GameTime time = world.currentTime();
GameCalendar calendar = (GameCalendar) world.get(ITEM.CALENDAR);
int yearNextTick = calendar.getYear(time.getTicks() + 1);
int yearThisTick = calendar.getYear(time.getTicks());
if (yearThisTick != yearNextTick) {
yearEnd();
}
// And a new month..
int monthThisTick = calendar.getMonth(time.getTicks());
int monthNextTick = calendar.getMonth(time.getTicks() + 1);
if (monthNextTick != monthThisTick) {
monthEnd();
}
/* calculate "ideal world" time for next tick */
nextModelUpdateDue = nextModelUpdateDue + (1000 / gameSpeed);
// int delay = (int)(nextModelUpdateDue - frameStartTime);
//
// /* wake up any waiting client threads - we could be
// * more aggressive, and only notify them if delay > 0? */
// this.notifyAll();
//
// try {
// if (delay > 0) {
// this.wait(delay);
// } else {
// this.wait(1);
// }
// } catch (InterruptedException e) {
// // do nothing
// }
ticksSinceUpdate++;
} else {
// try {
// //When the game is frozen we don't want to be spinning in a
// //loop.
// Thread.sleep(200);
// } catch (InterruptedException e) {
// // do nothing
// }
nextModelUpdateDue = System.currentTimeMillis();
}
}
}
Outgoing Methods (calls):
jfreerails.server.ServerGameModelImpl.updateGameTime
Javadoc:
No Javadoc available
Method code:
private void updateGameTime() {
moveExecuter.processMove(TimeTickMove.getMove(world));
}
Outgoing Methods (calls):
jfreerails.server.ServerGameModelImpl.write
Javadoc:
No Javadoc available
Method code:
public void write(ObjectOutputStream objectOut) throws IOException {
objectOut.writeObject(world);
objectOut.writeObject(serverAutomata);
/**
* save player private data
*/
for (int i = 0; i < world.getNumberOfPlayers(); i++) {
Player player = world.getPlayer(i);
player.saveSession(objectOut);
}
}
Outgoing Methods (calls):
jfreerails.server.ServerGameModelImpl.yearEnd
Javadoc:
/** This is called on the last tick of each year. */
Method code:
/** This is called on the last tick of each year. */
private void yearEnd() {
TrackMaintenanceMoveGenerator tmmg = new TrackMaintenanceMoveGenerator(
moveExecuter);
tmmg.update(world);
TrainMaintenanceMoveGenerator trainMaintenanceMoveGenerator = new TrainMaintenanceMoveGenerator(
moveExecuter);
trainMaintenanceMoveGenerator.update(world);
InterestChargeMoveGenerator interestChargeMoveGenerator = new InterestChargeMoveGenerator(
moveExecuter);
interestChargeMoveGenerator.update(world);
// Grow cities.
WorldDiffs wd = new WorldDiffs(world);
CityTilePositioner ctp = new CityTilePositioner(wd);
ctp.growCities();
WorldDiffMove move = new WorldDiffMove(world, wd, WorldDiffMove.Cause.YearEnd);
moveExecuter.processMove(move);
}
Outgoing Methods (calls):
jfreerails.server.TerrainRandomiser.getNewType
Javadoc:
No Javadoc available
Method code:
public int getNewType(int type) {
int newType = type;
double value;
double divide = 1.0 / terrainTypes.size();
// allow any terrain type to be drawn over except those listed in
// non_terrainTypes
if (!non_terrainTypes.contains(new Integer(newType))) {
if (Math.random() < CLEAR_PERCENTAGE) {
// make the tile Clear
return 4;
}
value = Math.random();
/*
* at the moment, this logic produces a balanced and even
* distribution of the different country tiles (currently 3).
* somehow it would be better to have the actual proportions of
* Farms, Jungle and Desert etc vary. dunno how.
*/
for (int i = 0; i < terrainTypes.size(); i++) {
if ((value > (i * divide)) && (value <= ((i + 1) * divide))) {
return terrainTypes.elementAt(i).intValue();
}
}
}
return newType;
}
No outgoing methods.
jfreerails.server.TileSetFactoryImpl.addTerrainTileTypesList
Javadoc:
No Javadoc available
Method code:
public void addTerrainTileTypesList(World w) {
try {
java.net.URL url = RunTypesParser.class
.getResource("/jfreerails/data/cargo_and_terrain.xml");
CargoAndTerrainParser.parse(url, new CargoAndTerrainHandlerImpl(w));
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException();
}
}
Outgoing Methods (calls):
jfreerails.server.TrackMaintenanceMoveGenerator.generateMove
Javadoc:
No Javadoc available
Method code:
public static AddTransactionMove generateMove(World w,
FreerailsPrincipal principal, Transaction.Category category) {
if (TRACK_MAINTENANCE != category && STATION_MAINTENANCE != category) {
throw new IllegalArgumentException(String.valueOf(category));
}
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, principal);
aggregator.setCategory(TRACK);
long amount = 0;
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
long maintenanceCost = trackRule.getMaintenanceCost().getAmount();
// Is the track type the category we are interested in?
boolean rightType = TRACK_MAINTENANCE == category ? !trackRule
.isStation() : trackRule.isStation();
if (rightType) {
aggregator.setType(i);
amount += maintenanceCost * aggregator.calculateQuantity()
/ TrackConfiguration.LENGTH_OF_STRAIGHT_TRACK_PIECE;
}
}
Transaction t = new Bill(new Money(amount), category);
return new AddTransactionMove(principal, t);
}
Outgoing Methods (calls):
jfreerails.server.TrackMaintenanceMoveGenerator.update
Javadoc:
No Javadoc available
Method code:
public void update(World w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
Move m = generateMove(w, principal, TRACK_MAINTENANCE);
moveReceiver.processMove(m);
m = generateMove(w, principal, STATION_MAINTENANCE);
moveReceiver.processMove(m);
}
}
Outgoing Methods (calls):
jfreerails.server.TrackMaintenanceMoveGeneratorTest.addTrack
Javadoc:
/** * Utility method to add the specified number of units of the specified track * type. */
Method code:
/**
* Utility method to add the specified number of units of the specified track
* type.
*/
private void addTrack(int trackType, int quantity) {
AddItemTransaction t = new AddItemTransaction(
Transaction.Category.TRACK, trackType, quantity, new Money(
trackType));
w.addTransaction(MapFixtureFactory.TEST_PRINCIPAL, t);
}
Outgoing Methods (calls):
jfreerails.server.TrackMaintenanceMoveGeneratorTest.calNumOfEachTrackType
Javadoc:
No Javadoc available
Method code:
private int[] calNumOfEachTrackType() {
int[] actual;
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, MapFixtureFactory.TEST_PRINCIPAL);
actual = new int[3];
aggregator.setType(0);
actual[0] = aggregator.calculateQuantity();
aggregator.setType(1);
actual[1] = aggregator.calculateQuantity();
aggregator.setType(2);
actual[2] = aggregator.calculateQuantity();
return actual;
}
Outgoing Methods (calls):
jfreerails.server.TrackMaintenanceMoveGeneratorTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
w = new WorldImpl(20, 20);
w.addPlayer(MapFixtureFactory.TEST_PLAYER);
MapFixtureFactory.generateTrackRuleList(w);
}
Outgoing Methods (calls):
jfreerails.server.TrackMaintenanceMoveGeneratorTest.testCalculateNumberOfEachTrackType
Javadoc:
No Javadoc available
Method code:
public void testCalculateNumberOfEachTrackType() {
int[] actual;
int[] expected;
actual = calNumOfEachTrackType();
/*
* actual = ItemsTransactionAggregator.calulateNumberOfEachTrackType(w,
* MapFixtureFactory.TEST_PRINCIPAL, 0);
*/
expected = new int[] { 0, 0, 0 }; // No track has been built yet.
assertTrue(Arrays.equals(expected, actual));
addTrack(0, 10);
actual = calNumOfEachTrackType();
expected = new int[] { 10, 0, 0 };
assertTrue(Arrays.equals(expected, actual));
addTrack(2, 20);
actual = calNumOfEachTrackType();
expected = new int[] { 10, 0, 20 };
assertTrue(Arrays.equals(expected, actual));
}
Outgoing Methods (calls):
jfreerails.server.TrainMaintenanceMoveGenerator.generateMove
Javadoc:
No Javadoc available
Method code:
private static AddTransactionMove generateMove(World w,
FreerailsPrincipal principal) {
NonNullElements trains = new NonNullElements(KEY.TRAINS, w, principal);
int numberOfTrains = trains.size();
long amount = numberOfTrains * 5000;
Transaction t = new Bill(new Money(amount),
Transaction.Category.TRAIN_MAINTENANCE);
return new AddTransactionMove(principal, t);
}
Outgoing Methods (calls):
jfreerails.server.TrainMaintenanceMoveGenerator.update
Javadoc:
No Javadoc available
Method code:
public void update(World w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
Move m = generateMove(w, principal);
moveReceiver.processMove(m);
}
}
Outgoing Methods (calls):
jfreerails.server.TrainPathFinder.hasNextInt
Javadoc:
No Javadoc available
Method code:
public boolean hasNextInt() {
boolean moving = stopsHandler.isTrainMoving();
if (moving) {
return trackExplorer.hasNextEdge();
}
mr.processMove(stopsHandler.getMoves());
return false;
}
Outgoing Methods (calls):
jfreerails.server.TrainPathFinder.initAutomaton
Javadoc:
No Javadoc available
Method code:
public void initAutomaton(MoveReceiver newMr) {
this.mr = newMr;
}
No outgoing methods.
jfreerails.server.TrainPathFinder.isTrainMoving
Javadoc:
No Javadoc available
Method code:
boolean isTrainMoving() {
boolean moving = stopsHandler.isTrainMoving();
mr.processMove(stopsHandler.getMoves());
return moving;
}
Outgoing Methods (calls):
jfreerails.server.TrainPathFinder.nextInt
Javadoc:
/** * @return a PositionOnTrack packed into an int */
Method code:
/**
* @return a PositionOnTrack packed into an int
*/
public int nextInt() {
PositionOnTrack tempP = new PositionOnTrack(trackExplorer.getPosition());
int x = tempP.getX();
int y = tempP.getY();
ImPoint targetPoint = stopsHandler.arrivesAtPoint(x, y);
int currentPosition = tempP.getOpposite().toInt();
ReadOnlyWorld world = trackExplorer.getWorld();
PositionOnTrack[] t = FlatTrackExplorer.getPossiblePositions(world,
targetPoint);
int[] targets = new int[t.length];
for (int i = 0; i < t.length; i++) {
int target = t[i].getOpposite().toInt();
if (target == currentPosition) {
stopsHandler.updateTarget();
}
targets[i] = target;
}
FlatTrackExplorer tempExplorer = new FlatTrackExplorer(world, tempP);
int next = pathFinder.findstep(currentPosition, targets, tempExplorer);
if (next == IncrementalPathFinder.PATH_NOT_FOUND) {
trackExplorer.nextEdge();
trackExplorer.moveForward();
return trackExplorer.getVertexConnectedByEdge();
}
tempP.setValuesFromInt(next);
tempP = tempP.getOpposite();
int nextPosition = tempP.toInt();
trackExplorer.setPosition(nextPosition);
mr.processMove(stopsHandler.getMoves());
return nextPosition;
}
Outgoing Methods (calls):
jfreerails.server.TrainUpdater.buildTrain
Javadoc:
No Javadoc available
Method code:
public void buildTrain(int engineTypeId, ImInts wagons, ImPoint p,
FreerailsPrincipal principal, ReadOnlyWorld world) {
// If there are no wagons, setup an automatic schedule.
boolean autoSchedule = 0 == wagons.size();
ImmutableSchedule is = generateInitialSchedule(principal, world,
autoSchedule);
PreMove addTrain = new AddTrainPreMove(engineTypeId, wagons, p,
principal, is);
Move m = addTrain.generateMove(world);
moveReceiver.processMove(m);
}
Outgoing Methods (calls):
jfreerails.server.TrainUpdater.buildTrains
Javadoc:
/** * Iterator over the stations and build trains at any that have their * production field set. * */
Method code:
/**
* Iterator over the stations and build trains at any that have their
* production field set.
*
*/
void buildTrains(ReadOnlyWorld world) {
for (int k = 0; k < world.getNumberOfPlayers(); k++) {
FreerailsPrincipal principal = world.getPlayer(k).getPrincipal();
for (int i = 0; i < world.size(principal, KEY.STATIONS); i++) {
StationModel station = (StationModel) world.get(principal,
KEY.STATIONS, i);
if (null != station) {
ImList<PlannedTrain> production = station
.getProduction();
if (production.size() > 0) {
ImPoint p = new ImPoint(station.x, station.y);
for (int j = 0; j < production.size(); j++) {
int engineType = production.get(j).getEngineType();
ImInts wagonTypes = production.get(j)
.getWagonTypes();
this.buildTrain(engineType, wagonTypes, p,
principal, world);
// TrainMover trainMover =
// this.buildTrain(engineType, wagonTypes, p,
// principal, world);
// this.addTrainMover(trainMover);
}
ChangeProductionAtEngineShopMove move = new ChangeProductionAtEngineShopMove(
production,
new ImList<PlannedTrain>(), i,
principal);
moveReceiver.processMove(move);
}
}
}
}
}
Outgoing Methods (calls):
jfreerails.server.TrainUpdater.generateInitialSchedule
Javadoc:
No Javadoc available
Method code:
private ImmutableSchedule generateInitialSchedule(
FreerailsPrincipal principal, ReadOnlyWorld world,
boolean autoSchedule) {
WorldIterator wi = new NonNullElements(KEY.STATIONS, world, principal);
MutableSchedule s = new MutableSchedule();
// Add upto 4 stations to the schedule.
while (wi.next() && s.getNumOrders() < 5) {
TrainOrdersModel orders = new TrainOrdersModel(wi.getIndex(), null,
false, autoSchedule);
s.addOrder(orders);
}
s.setOrderToGoto(0);
ImmutableSchedule is = s.toImmutableSchedule();
return is;
}
Outgoing Methods (calls):
jfreerails.server.TrainUpdater.initAutomaton
Javadoc:
No Javadoc available
Method code:
public void initAutomaton(MoveReceiver mr) {
moveReceiver = mr;
}
No outgoing methods.
jfreerails.server.TrainUpdater.initTarget
Javadoc:
/** * @return a move that initialises the trains schedule. */
Method code:
/**
* @return a move that initialises the trains schedule.
*/
public static Move initTarget(TrainModel train, int trainID,
ImmutableSchedule currentSchedule, FreerailsPrincipal principal) {
Vector<Move> moves = new Vector<Move>();
int scheduleID = train.getScheduleID();
MutableSchedule schedule = new MutableSchedule(currentSchedule);
ImInts wagonsToAdd = schedule.getWagonsToAdd();
if (null != wagonsToAdd) {
int engine = train.getEngineType();
ChangeTrainMove move = ChangeTrainMove.generateMove(trainID, train,
engine, wagonsToAdd, principal);
moves.add(move);
}
schedule.gotoNextStation();
ImmutableSchedule newSchedule = schedule.toImmutableSchedule();
ChangeTrainScheduleMove move = new ChangeTrainScheduleMove(scheduleID,
currentSchedule, newSchedule, principal);
moves.add(move);
return new CompositeMove(moves.toArray(new Move[1]));
}
Outgoing Methods (calls):
jfreerails.server.TrainUpdater.moveTrain
Javadoc:
No Javadoc available
Method code:
private void moveTrain(ReadOnlyWorld world, FreerailsPrincipal principal, int trainId) {
MoveTrainPreMove preMove = new MoveTrainPreMove(trainId, principal);
if (preMove.isUpdateDue(world)) {
TrainAccessor ta = new TrainAccessor(world, principal, trainId);
if (!ta.trackExists()) {
System.out.println("Track under train does not exist. Retiring train..");
this.retireTrain(world, principal, trainId);
} else {
Move m = preMove.generateMove(world);
moveReceiver.processMove(m);
}
}
}
Outgoing Methods (calls):
jfreerails.server.TrainUpdater.moveTrains
Javadoc:
No Javadoc available
Method code:
void moveTrains(ReadOnlyWorld world) {
int time = world.currentTime().getTicks();
for (int k = 0; k < world.getNumberOfPlayers(); k++) {
FreerailsPrincipal principal = world.getPlayer(k).getPrincipal();
//If a train is moving, we want it to keep moving rather than stop
//to allow an already stationary train to start moving. To achieve this
//we process moving trains first.
ArrayList<Integer> movingTrains = new ArrayList<Integer>();
ArrayList<Integer> stoppedTrains = new ArrayList<Integer>();
for (int i = 0; i < world.size(principal, KEY.TRAINS); i++) {
TrainModel train = (TrainModel) world.get(principal,
KEY.TRAINS, i);
if (null == train) {
continue;
}
TrainAccessor ta = new TrainAccessor(world, principal, i);
if (ta.isMoving(time)) {
movingTrains.add(i);
} else {
stoppedTrains.add(i);
}
}
for (int trainId : movingTrains) {
moveTrain(world, principal, trainId);
}
for (int trainId : stoppedTrains) {
moveTrain(world, principal, trainId);
}
}
}
Outgoing Methods (calls):
jfreerails.server.TrainUpdater.retireTrain
Javadoc:
No Javadoc available
Method code:
private void retireTrain(ReadOnlyWorld world, FreerailsPrincipal principal, int trainId) {
Move m = RemoveTrainMove.getInstance(trainId, principal, world);
moveReceiver.processMove(m);
}
Outgoing Methods (calls):
jfreerails.server.TrainUpdater.setInitialTrainPosition
Javadoc:
No Javadoc available
Method code:
static TrainPositionOnMap setInitialTrainPosition(TrainModel train,
FreerailsPathIterator from) {
int trainLength = train.getLength();
PathWalker fromPathWalker = new PathWalkerImpl(from);
assert fromPathWalker.canStepForward();
fromPathWalker.stepForward(trainLength);
TrainPositionOnMap initialPosition = TrainPositionOnMap
.createInSameDirectionAsPath(fromPathWalker);
return initialPosition;
}
Outgoing Methods (calls):
jfreerails.server.TrainUpdater.trainPos2Tiles
Javadoc:
/** * Converts a train's position on the map into an array of tile coordinates. * Each tile coordinate is calculated by dividing the train's X and Y positions * by the TILE_WIDTH (30) to map the continuous position to a grid of tiles. * * @param pos The train's position on the map, which contains methods to retrieve * the X, Y coordinates, and the length (number of tiles the train occupies) * @return An array of ImPoint objects representing the tile coordinates for each * segment of the train's position */
Method code:
public static ImPoint[] trainPos2Tiles(TrainPositionOnMap pos) {
ImPoint[] returnValue = new ImPoint[pos.getLength()];
final int TILE_WIDTH = 30;
for (int i = 0; i < returnValue.length; i++) {
returnValue[i] = new ImPoint(pos.getX(i) / TILE_WIDTH, pos.getY(i)
/ TILE_WIDTH);
}
return returnValue;
}
Outgoing Methods (calls):
jfreerails.server.common.TileSetFactory.addTerrainTileTypesList
Javadoc:
No Javadoc available
Method code:
void addTerrainTileTypesList(World w);
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandler.end_Cargo_Types
Javadoc:
/** * A container element end event handling method. * */
Method code:
/**
* A container element end event handling method.
*
*/
public void end_Cargo_Types() throws SAXException;
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandler.end_Terrain_Types
Javadoc:
/** * A container element end event handling method. * */
Method code:
/**
* A container element end event handling method.
*
*/
public void end_Terrain_Types() throws SAXException;
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandler.end_Tile
Javadoc:
/** * A container element end event handling method. * */
Method code:
/**
* A container element end event handling method.
*
*/
public void end_Tile() throws SAXException;
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandler.end_Types
Javadoc:
/** * A container element end event handling method. * */
Method code:
/**
* A container element end event handling method.
*
*/
public void end_Types() throws SAXException;
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandler.handle_Cargo
Javadoc:
/** * An empty element event handling method. * */
Method code:
/**
* An empty element event handling method.
*
*/
public void handle_Cargo(final Attributes meta) throws SAXException;
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandler.handle_Consumes
Javadoc:
/** * An empty element event handling method. * */
Method code:
/**
* An empty element event handling method.
*
*/
public void handle_Consumes(final Attributes meta) throws SAXException;
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandler.handle_Converts
Javadoc:
/** * An empty element event handling method. * */
Method code:
/**
* An empty element event handling method.
*
*/
public void handle_Converts(final Attributes meta) throws SAXException;
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandler.handle_Produces
Javadoc:
/** * An empty element event handling method. * */
Method code:
/**
* An empty element event handling method.
*
*/
public void handle_Produces(final Attributes meta) throws SAXException;
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandler.start_Cargo_Types
Javadoc:
/** * A container element start event handling method. * * @param meta * attributes * */
Method code:
/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/
public void start_Cargo_Types(final Attributes meta) throws SAXException;
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandler.start_Terrain_Types
Javadoc:
/** * A container element start event handling method. * * @param meta * attributes * */
Method code:
/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/
public void start_Terrain_Types(final Attributes meta) throws SAXException;
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandler.start_Tile
Javadoc:
/** * A container element start event handling method. * * @param meta * attributes * */
Method code:
/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/
public void start_Tile(final Attributes meta) throws SAXException;
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandler.start_Types
Javadoc:
/** * A container element start event handling method. * * @param meta * attributes * */
Method code:
/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/
public void start_Types(final Attributes meta) throws SAXException;
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandlerImpl.end_Cargo_Types
Javadoc:
No Javadoc available
Method code:
public void end_Cargo_Types() throws SAXException {
// no need to do anything here.
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandlerImpl.end_Terrain_Types
Javadoc:
No Javadoc available
Method code:
public void end_Terrain_Types() throws SAXException {
// no need to do anything here.
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandlerImpl.end_Tile
Javadoc:
No Javadoc available
Method code:
public void end_Tile() throws SAXException {
Consumption[] consumes = new Consumption[typeConsumes.size()];
for (int i = 0; i < typeConsumes.size(); i++) {
consumes[i] = typeConsumes.get(i);
}
Production[] produces = new Production[typeProduces.size()];
for (int i = 0; i < typeProduces.size(); i++) {
produces[i] = typeProduces.get(i);
}
Conversion[] converts = new Conversion[typeConverts.size()];
for (int i = 0; i < typeConverts.size(); i++) {
converts[i] = typeConverts.get(i);
}
TileTypeImpl tileType = new TileTypeImpl(tileRGB, tileCategory, tileID,
tileROW, produces, consumes, converts, tileBuildCost);
world.add(SKEY.TERRAIN_TYPES, tileType);
}
Outgoing Methods (calls):
jfreerails.server.parser.CargoAndTerrainHandlerImpl.end_Types
Javadoc:
No Javadoc available
Method code:
public void end_Types() throws SAXException {
// no need to do anything here.
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandlerImpl.handle_Cargo
Javadoc:
No Javadoc available
Method code:
public void handle_Cargo(final Attributes meta) throws SAXException {
String cargoID = meta.getValue("id");
String cargoCategory = meta.getValue("Category");
int unitWeight = Integer.parseInt(meta.getValue("unitWeight"));
CargoType cargoType = new CargoType(unitWeight, cargoID, Categories
.getCategory(cargoCategory));
int cargoNumber = world.size(SKEY.CARGO_TYPES);
cargoName2cargoTypeNumber.put(cargoID, new Integer(cargoNumber));
world.add(SKEY.CARGO_TYPES, cargoType);
}
Outgoing Methods (calls):
jfreerails.server.parser.CargoAndTerrainHandlerImpl.handle_Consumes
Javadoc:
No Javadoc available
Method code:
public void handle_Consumes(final Attributes meta) throws SAXException {
int cargoConsumed = string2CargoID(meta.getValue("Cargo"));
String prerequisiteString = meta.getValue("Prerequisite");
// "Prerequisite" is an optional attribute, so may be null.
int prerequisiteForConsumption = (null == prerequisiteString ? 1
: Integer.parseInt(prerequisiteString));
Consumption consumption = new Consumption(cargoConsumed,
prerequisiteForConsumption);
typeConsumes.add(consumption);
}
Outgoing Methods (calls):
jfreerails.server.parser.CargoAndTerrainHandlerImpl.handle_Converts
Javadoc:
No Javadoc available
Method code:
public void handle_Converts(final Attributes meta) throws SAXException {
String inputCargo = meta.getValue("input");
String outputCargo = meta.getValue("output");
int input = string2CargoID(inputCargo);
int output = string2CargoID(outputCargo);
Conversion conversion = new Conversion(input, output);
typeConverts.add(conversion);
}
Outgoing Methods (calls):
jfreerails.server.parser.CargoAndTerrainHandlerImpl.handle_Produces
Javadoc:
No Javadoc available
Method code:
public void handle_Produces(final Attributes meta) throws SAXException {
int cargoProduced = string2CargoID(meta.getValue("Cargo"));
int rateOfProduction = Integer.parseInt(meta.getValue("Rate"));
Production production = new Production(cargoProduced, rateOfProduction);
typeProduces.add(production);
}
Outgoing Methods (calls):
jfreerails.server.parser.CargoAndTerrainHandlerImpl.start_Cargo_Types
Javadoc:
No Javadoc available
Method code:
public void start_Cargo_Types(final Attributes meta) throws SAXException {
// no need to do anything here.
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandlerImpl.start_Terrain_Types
Javadoc:
No Javadoc available
Method code:
public void start_Terrain_Types(final Attributes meta) throws SAXException {
// no need to do anything here.
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandlerImpl.start_Tile
Javadoc:
No Javadoc available
Method code:
public void start_Tile(final Attributes meta) throws SAXException {
typeConsumes.clear();
typeProduces.clear();
typeConverts.clear();
tileID = meta.getValue("id");
tileCategory = TerrainType.Category.valueOf(meta.getValue("Category"));
String rgbString = meta.getValue("rgb");
tileRGB = string2RGBValue(rgbString);
String buildCostString = meta.getValue("build_cost");
if (null != buildCostString) {
tileBuildCost = Integer.parseInt(buildCostString);
} else {
tileBuildCost = -1;
}
// Check if another type is already using this rgb value..
Integer rgbInteger = new Integer(tileRGB);
if (rgbValuesAlreadyUsed.contains(rgbInteger)) {
throw new SAXException(tileID + " can't using rgb value "
+ rgbString
+ " because it is being used by another tile type!");
}
rgbValuesAlreadyUsed.add(rgbInteger);
tileROW = Integer.parseInt(meta.getValue("right-of-way"));
}
Outgoing Methods (calls):
jfreerails.server.parser.CargoAndTerrainHandlerImpl.start_Types
Javadoc:
/** * This method is called when the XML parser encounters the start of the &lt;Types&gt; element. * It is part of the process for parsing cargo and terrain types defined in the XML configuration. * No action is required here as the actual processing of type definitions is handled by subsequent methods. * * @param meta The attributes of the &lt;Types&gt; XML element, which may contain metadata about the types. * @throws SAXException If an error occurs during XML parsing while processing the &lt;Types&gt; element. * * @see CargoAndTerrainHandler * @see CargoAndTerrainParser */
Method code:
public void start_Types(final Attributes meta) throws SAXException {
// no need to do anything here.
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandlerImpl.string2CargoID
Javadoc:
/** Returns the index number of the cargo with the specified name. */
Method code:
/** Returns the index number of the cargo with the specified name. */
private int string2CargoID(String cargoName) throws SAXException {
if (cargoName2cargoTypeNumber.containsKey(cargoName)) {
Integer integer = cargoName2cargoTypeNumber.get(cargoName);
return integer.intValue();
}
throw new SAXException("Unknown cargo type: " + cargoName);
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainHandlerImpl.string2RGBValue
Javadoc:
No Javadoc available
Method code:
private int string2RGBValue(String temp_number) {
int rgb = Integer.parseInt(temp_number, 16);
/*
* We need to change the format of the rgb value to the same one as used
* by the the BufferedImage that stores the map. See
* jfreerails.common.Map
*/
rgb = new java.awt.Color(rgb).getRGB();
return rgb;
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainParser.characters
Javadoc:
/** * This SAX interface method is implemented by the parser. * */
Method code:
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void characters(char[] chars, int start, int len)
throws SAXException {
buffer.append(chars, start, len);
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainParser.dispatch
Javadoc:
No Javadoc available
Method code:
private void dispatch(final boolean fireOnlyIfMixed) throws SAXException {
if (fireOnlyIfMixed && buffer.length() == 0) {
return; // skip it
}
buffer.delete(0, buffer.length());
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainParser.endDocument
Javadoc:
/** * This SAX interface method is implemented by the parser. * */
Method code:
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void endDocument() throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainParser.endElement
Javadoc:
/** * This SAX interface method is implemented by the parser. * */
Method code:
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void endElement(java.lang.String ns, java.lang.String name,
java.lang.String qname) throws SAXException {
dispatch(false);
context.pop();
if ("Tile".equals(name)) {
handler.end_Tile();
} else if ("Cargo_Types".equals(name)) {
handler.end_Cargo_Types();
} else if ("Terrain_Types".equals(name)) {
handler.end_Terrain_Types();
} else if ("Types".equals(name)) {
handler.end_Types();
}
}
Outgoing Methods (calls):
jfreerails.server.parser.CargoAndTerrainParser.endPrefixMapping
Javadoc:
/** * This SAX interface method is implemented by the parser. * */
Method code:
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void endPrefixMapping(final java.lang.String prefix)
throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainParser.getDefaultErrorHandler
Javadoc:
/** * Creates default error handler used by this parser. * * @return org.xml.sax.ErrorHandler implementation * */
Method code:
/**
* Creates default error handler used by this parser.
*
* @return org.xml.sax.ErrorHandler implementation
*
*/
protected ErrorHandler getDefaultErrorHandler() {
return new ErrorHandler() {
public void error(SAXParseException ex) throws SAXException {
if (context.isEmpty()) {
logger.severe("Missing DOCTYPE.");
}
throw ex;
}
public void fatalError(SAXParseException ex) throws SAXException {
throw ex;
}
public void warning(SAXParseException ex) throws SAXException {
// ignore
}
};
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainParser.ignorableWhitespace
Javadoc:
/** * This SAX interface method is implemented by the parser. * */
Method code:
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void ignorableWhitespace(char[] chars, int start, int len)
throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainParser.parse
Javadoc:
No Javadoc available
Method code:
private static void parse(final InputSource input,
final CargoAndTerrainParser recognizer) throws SAXException,
javax.xml.parsers.ParserConfigurationException, java.io.IOException {
javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory
.newInstance();
factory.setValidating(true); // the code was generated according DTD
factory.setNamespaceAware(true); // the code was generated according
// DTD
XMLReader parser = factory.newSAXParser().getXMLReader();
parser.setContentHandler(recognizer);
parser.setErrorHandler(recognizer.getDefaultErrorHandler());
if (recognizer.resolver != null) {
parser.setEntityResolver(recognizer.resolver);
}
parser.parse(input);
}
Outgoing Methods (calls):
jfreerails.server.parser.CargoAndTerrainParser.processingInstruction
Javadoc:
/** * This SAX interface method is implemented by the parser. * */
Method code:
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void processingInstruction(java.lang.String target,
java.lang.String data) throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainParser.setDocumentLocator
Javadoc:
/** * This SAX interface method is implemented by the parser. * */
Method code:
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void setDocumentLocator(Locator locator) {
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainParser.skippedEntity
Javadoc:
/** * This SAX interface method is implemented by the parser. * */
Method code:
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void skippedEntity(java.lang.String name) throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainParser.startDocument
Javadoc:
/** * This SAX interface method is implemented by the parser. * */
Method code:
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void startDocument() throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.CargoAndTerrainParser.startElement
Javadoc:
/** * This SAX interface method is implemented by the parser. * */
Method code:
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void startElement(java.lang.String ns, java.lang.String name,
java.lang.String qname, Attributes attrs) throws SAXException {
dispatch(true);
context.push(new Object[] { qname,
new org.xml.sax.helpers.AttributesImpl(attrs) });
if ("Converts".equals(name)) {
handler.handle_Converts(attrs);
} else if ("Tile".equals(name)) {
handler.start_Tile(attrs);
} else if ("Cargo".equals(name)) {
handler.handle_Cargo(attrs);
} else if ("Cargo_Types".equals(name)) {
handler.start_Cargo_Types(attrs);
} else if ("Terrain_Types".equals(name)) {
handler.start_Terrain_Types(attrs);
} else if ("Types".equals(name)) {
handler.start_Types(attrs);
} else if ("Consumes".equals(name)) {
handler.handle_Consumes(attrs);
} else if ("Produces".equals(name)) {
handler.handle_Produces(attrs);
}
}
Outgoing Methods (calls):
jfreerails.server.parser.CargoAndTerrainParser.startPrefixMapping
Javadoc:
/** * This SAX interface method is implemented by the parser. * */
Method code:
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void startPrefixMapping(final java.lang.String prefix,
final java.lang.String uri) throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.RunTypesParser.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
try {
java.net.URL url = RunTypesParser.class
.getResource("/jfreerails/data/cargo_and_terrain.xml");
CargoAndTerrainParser.parse(url, new CargoAndTerrainHandlerImpl(
new WorldImpl()));
logger.info("It worked");
} catch (Exception e) {
e.printStackTrace();
}
}
Outgoing Methods (calls):
jfreerails.server.parser.Track_TilesHandler.end_CanOnlyBuildOnTheseTerrainTypes
Javadoc:
/** * A container element end event handling method. */
Method code:
/**
* A container element end event handling method.
*/
void end_CanOnlyBuildOnTheseTerrainTypes() throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.end_CannotBuildOnTheseTerrainTypes
Javadoc:
/** * A container element end event handling method. */
Method code:
/**
* A container element end event handling method.
*/
void end_CannotBuildOnTheseTerrainTypes() throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.end_ListOfLegalRoutesAcrossNode
Javadoc:
/** * A container element end event handling method. */
Method code:
/**
* A container element end event handling method.
*/
void end_ListOfLegalRoutesAcrossNode() throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.end_ListOfTrackPieceTemplates
Javadoc:
/** * A container element end event handling method. */
Method code:
/**
* A container element end event handling method.
*/
void end_ListOfTrackPieceTemplates() throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.end_Tiles
Javadoc:
/** * A container element end event handling method. */
Method code:
/**
* A container element end event handling method.
*/
void end_Tiles() throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.end_TrackPieceTemplate
Javadoc:
/** * A container element end event handling method. */
Method code:
/**
* A container element end event handling method.
*/
void end_TrackPieceTemplate() throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.end_TrackSet
Javadoc:
/** * A container element end event handling method. */
Method code:
/**
* A container element end event handling method.
*/
void end_TrackSet() throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.end_TrackType
Javadoc:
/** * A container element end event handling method. */
Method code:
/**
* A container element end event handling method.
*/
void end_TrackType() throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.handle_LegalRouteAcrossNode
Javadoc:
/** * An empty element event handling method. */
Method code:
/**
* An empty element event handling method.
*/
void handle_LegalRouteAcrossNode(final Attributes meta) throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.handle_TerrainType
Javadoc:
/** * An empty element event handling method. */
Method code:
/**
* An empty element event handling method.
*/
void handle_TerrainType(final Attributes meta) throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.start_CanOnlyBuildOnTheseTerrainTypes
Javadoc:
/** * A container element start event handling method. * * @param meta * attributes */
Method code:
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_CanOnlyBuildOnTheseTerrainTypes(final Attributes meta)
throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.start_CannotBuildOnTheseTerrainTypes
Javadoc:
/** * A container element start event handling method. * * @param meta * attributes */
Method code:
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_CannotBuildOnTheseTerrainTypes(final Attributes meta)
throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.start_ListOfLegalRoutesAcrossNode
Javadoc:
/** * A container element start event handling method. * * @param meta * attributes */
Method code:
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_ListOfLegalRoutesAcrossNode(final Attributes meta)
throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.start_ListOfTrackPieceTemplates
Javadoc:
/** * A container element start event handling method. * * @param meta * attributes */
Method code:
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_ListOfTrackPieceTemplates(final Attributes meta)
throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.start_Tiles
Javadoc:
/** * A container element start event handling method. * * @param meta * attributes */
Method code:
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_Tiles(final Attributes meta) throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.start_TrackPieceTemplate
Javadoc:
/** * A container element start event handling method. * * @param meta * attributes */
Method code:
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_TrackPieceTemplate(final Attributes meta) throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.start_TrackSet
Javadoc:
/** * A container element start event handling method. * * @param meta * attributes */
Method code:
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_TrackSet(final Attributes meta) throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandler.start_TrackType
Javadoc:
/** * A container element start event handling method. * * @param meta * attributes */
Method code:
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_TrackType(final Attributes meta) throws SAXException;
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.addTrackRules
Javadoc:
No Javadoc available
Method code:
public void addTrackRules(World w) {
for (int i = 0; i < this.ruleList.size(); i++) {
TrackRule r = ruleList.get(i);
w.add(SKEY.TRACK_RULES, r);
}
}
Outgoing Methods (calls):
jfreerails.server.parser.Track_TilesHandlerImpl.end_CanOnlyBuildOnTheseTerrainTypes
Javadoc:
No Javadoc available
Method code:
public void end_CanOnlyBuildOnTheseTerrainTypes() throws SAXException {
legalTrackPlacement = new LegalTrackPlacement(terrainTypes,
LegalTrackPlacement.PlacementRule.ONLY_ON_THESE);
terrainTypes = null;
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.end_CannotBuildOnTheseTerrainTypes
Javadoc:
No Javadoc available
Method code:
public void end_CannotBuildOnTheseTerrainTypes() throws SAXException {
legalTrackPlacement = new LegalTrackPlacement(terrainTypes,
LegalTrackPlacement.PlacementRule.ANYWHERE_EXCEPT_ON_THESE);
terrainTypes = null;
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.end_ListOfLegalRoutesAcrossNode
Javadoc:
No Javadoc available
Method code:
public void end_ListOfLegalRoutesAcrossNode() throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.end_ListOfTrackPieceTemplates
Javadoc:
No Javadoc available
Method code:
public void end_ListOfTrackPieceTemplates() throws SAXException {
legalTrackConfigurations = new jfreerails.world.track.LegalTrackConfigurations(
maxConsequ, legalTemplates);
legalTemplates = null;
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.end_Tiles
Javadoc:
No Javadoc available
Method code:
public void end_Tiles() throws SAXException {
// Sort the track tiles by category then price.
Collections.sort(ruleList);
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.end_TrackPieceTemplate
Javadoc:
No Javadoc available
Method code:
public void end_TrackPieceTemplate() throws SAXException {
// do nothing.
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.end_TrackSet
Javadoc:
No Javadoc available
Method code:
public void end_TrackSet() throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.end_TrackType
Javadoc:
No Javadoc available
Method code:
public void end_TrackType() throws SAXException {
TrackRuleImpl trackRuleImpl = new jfreerails.world.track.TrackRuleImpl(
trackRuleProperties, legalTrackConfigurations,
legalTrackPlacement);
ruleList.add(trackRuleImpl);
legalTrackConfigurations = null;
trackRuleProperties = null;
legalTrackPlacement = null;
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.getRuleList
Javadoc:
No Javadoc available
Method code:
public List<TrackRule> getRuleList() {
return ruleList;
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.handle_LegalRouteAcrossNode
Javadoc:
No Javadoc available
Method code:
public void handle_LegalRouteAcrossNode(final Attributes meta)
throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.handle_TerrainType
Javadoc:
No Javadoc available
Method code:
public void handle_TerrainType(final Attributes meta) throws SAXException {
TerrainType.Category cat = TerrainType.Category.valueOf(meta
.getValue("name"));
terrainTypes.add(cat);
}
Outgoing Methods (calls):
jfreerails.server.parser.Track_TilesHandlerImpl.start_CanOnlyBuildOnTheseTerrainTypes
Javadoc:
No Javadoc available
Method code:
public void start_CanOnlyBuildOnTheseTerrainTypes(final Attributes meta)
throws SAXException {
terrainTypes = new HashSet<TerrainType.Category>();
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.start_CannotBuildOnTheseTerrainTypes
Javadoc:
No Javadoc available
Method code:
public void start_CannotBuildOnTheseTerrainTypes(final Attributes meta)
throws SAXException {
terrainTypes = new java.util.HashSet<TerrainType.Category>();
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.start_ListOfLegalRoutesAcrossNode
Javadoc:
No Javadoc available
Method code:
public void start_ListOfLegalRoutesAcrossNode(final Attributes meta)
throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.start_ListOfTrackPieceTemplates
Javadoc:
No Javadoc available
Method code:
public void start_ListOfTrackPieceTemplates(final Attributes meta)
throws SAXException {
legalTemplates = new ArrayList<String>();
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.start_Tiles
Javadoc:
No Javadoc available
Method code:
public void start_Tiles(final Attributes meta) throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.start_TrackPieceTemplate
Javadoc:
No Javadoc available
Method code:
public void start_TrackPieceTemplate(final Attributes meta)
throws SAXException {
legalTemplates.add(meta.getValue("trackTemplate"));
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.start_TrackSet
Javadoc:
No Javadoc available
Method code:
public void start_TrackSet(final Attributes meta) throws SAXException {
ruleList = new ArrayList<TrackRule>();
}
No outgoing methods.
jfreerails.server.parser.Track_TilesHandlerImpl.start_TrackType
Javadoc:
No Javadoc available
Method code:
public void start_TrackType(final Attributes meta) throws SAXException {
int rGBvalue;
String rgbString = meta.getValue("RGBvalue");
rGBvalue = Integer.parseInt(rgbString, 16);
/*
* We need to change the format of the rgb value to the same one as used
* by the the BufferedImage that stores the map. See
* jfreerails.common.Map
*/
rGBvalue = new java.awt.Color(rGBvalue).getRGB();
TrackRule.TrackCategories category = TrackRule.TrackCategories
.valueOf(meta.getValue("category"));
boolean enableDoubleTrack = Boolean.valueOf(
meta.getValue("doubleTrack")).booleanValue();
String typeName = meta.getValue("type");
maxConsequ = Integer.parseInt(meta.getValue("maxConsecuativePieces"));
String stationRadiusString = meta.getValue("stationRadius");
int stationRadius;
if (null != stationRadiusString) {
stationRadius = Integer.parseInt(stationRadiusString);
} else {
stationRadius = 0;
}
String priceString = meta.getValue("price");
int price = Integer.parseInt(priceString);
String fixedCostString = meta.getValue("fixedCost");
int fixedCost;
if (null != fixedCostString) {
fixedCost = Integer.parseInt(fixedCostString);
} else {
fixedCost = 0;
}
String maintenanceString = meta.getValue("maintenance");
int maintenance = Integer.parseInt(maintenanceString);
trackRuleProperties = new TrackRuleProperties(rGBvalue,
enableDoubleTrack, typeName, category, stationRadius, price,
maintenance, fixedCost);
}
Outgoing Methods (calls):
jfreerails.server.parser.Track_TilesParser.characters
Javadoc:
No Javadoc available
Method code:
public void characters(char[] chars, int start, int len)
throws SAXException {
buffer.append(chars, start, len);
}
No outgoing methods.
jfreerails.server.parser.Track_TilesParser.dispatch
Javadoc:
No Javadoc available
Method code:
private void dispatch(final boolean fireOnlyIfMixed) throws SAXException {
if (fireOnlyIfMixed && buffer.length() == 0) {
return; // skip it
}
buffer.delete(0, buffer.length());
}
No outgoing methods.
jfreerails.server.parser.Track_TilesParser.endDocument
Javadoc:
No Javadoc available
Method code:
public void endDocument() throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.Track_TilesParser.endElement
Javadoc:
No Javadoc available
Method code:
public void endElement(java.lang.String ns, java.lang.String name,
java.lang.String qname) throws SAXException {
dispatch(false);
context.pop();
if ("CanOnlyBuildOnTheseTerrainTypes".equals(qname)) {
handler.end_CanOnlyBuildOnTheseTerrainTypes();
} else if ("ListOfTrackPieceTemplates".equals(qname)) {
handler.end_ListOfTrackPieceTemplates();
} else if ("ListOfLegalRoutesAcrossNode".equals(qname)) {
handler.end_ListOfLegalRoutesAcrossNode();
} else if ("CannotBuildOnTheseTerrainTypes".equals(qname)) {
handler.end_CannotBuildOnTheseTerrainTypes();
} else if ("TrackType".equals(qname)) {
handler.end_TrackType();
} else if ("Tiles".equals(qname)) {
handler.end_Tiles();
} else if ("TrackPieceTemplate".equals(qname)) {
handler.end_TrackPieceTemplate();
} else if ("TrackSet".equals(qname)) {
handler.end_TrackSet();
}
}
Outgoing Methods (calls):
jfreerails.server.parser.Track_TilesParser.endPrefixMapping
Javadoc:
No Javadoc available
Method code:
public void endPrefixMapping(final java.lang.String prefix)
throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.Track_TilesParser.getDefaultErrorHandler
Javadoc:
No Javadoc available
Method code:
private org.xml.sax.ErrorHandler getDefaultErrorHandler() {
return new org.xml.sax.ErrorHandler() {
public void error(org.xml.sax.SAXParseException ex)
throws SAXException {
if (context.isEmpty()) {
logger.severe("Missing DOCTYPE.");
}
throw ex;
}
public void fatalError(org.xml.sax.SAXParseException ex)
throws SAXException {
throw ex;
}
public void warning(org.xml.sax.SAXParseException ex)
throws SAXException {
// ignore
}
};
}
No outgoing methods.
jfreerails.server.parser.Track_TilesParser.ignorableWhitespace
Javadoc:
No Javadoc available
Method code:
public void ignorableWhitespace(char[] chars, int start, int len)
throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.Track_TilesParser.parse
Javadoc:
No Javadoc available
Method code:
private static void parse(final InputSource input,
final Track_TilesParser recognizer) throws SAXException,
ParserConfigurationException, IOException {
javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory
.newInstance();
factory.setValidating(true); // the code was generated according DTD
factory.setNamespaceAware(false); // the code was generated according
// DTD
org.xml.sax.XMLReader parser = factory.newSAXParser().getXMLReader();
parser.setContentHandler(recognizer);
parser.setErrorHandler(recognizer.getDefaultErrorHandler());
parser.parse(input);
}
Outgoing Methods (calls):
jfreerails.server.parser.Track_TilesParser.processingInstruction
Javadoc:
No Javadoc available
Method code:
public void processingInstruction(java.lang.String target,
java.lang.String data) throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.Track_TilesParser.setDocumentLocator
Javadoc:
No Javadoc available
Method code:
public void setDocumentLocator(org.xml.sax.Locator locator) {
}
No outgoing methods.
jfreerails.server.parser.Track_TilesParser.skippedEntity
Javadoc:
/** * Callback method invoked when an XML entity is skipped during parsing. * * @param name The name of the XML entity that was skipped. * @throws SAXException If an error occurs while handling the skipped entity. */
Method code:
public void skippedEntity(java.lang.String name) throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.Track_TilesParser.startDocument
Javadoc:
/** * Called when the parsing of a document starts. * Initializes any necessary state or resources required for parsing the track tiles data. * * @throws SAXException if an error occurs during document initialization. */
Method code:
public void startDocument() throws SAXException {
}
No outgoing methods.
jfreerails.server.parser.Track_TilesParser.startElement
Javadoc:
No Javadoc available
Method code:
public void startElement(java.lang.String ns, java.lang.String name,
java.lang.String qname, org.xml.sax.Attributes attrs)
throws SAXException {
dispatch(true);
context.push(new Object[] { qname,
new org.xml.sax.helpers.AttributesImpl(attrs) });
if ("CanOnlyBuildOnTheseTerrainTypes".equals(qname)) {
handler.start_CanOnlyBuildOnTheseTerrainTypes(attrs);
} else if ("ListOfTrackPieceTemplates".equals(qname)) {
handler.start_ListOfTrackPieceTemplates(attrs);
} else if ("ListOfLegalRoutesAcrossNode".equals(qname)) {
handler.start_ListOfLegalRoutesAcrossNode(attrs);
} else if ("LegalRouteAcrossNode".equals(qname)) {
handler.handle_LegalRouteAcrossNode(attrs);
} else if ("CannotBuildOnTheseTerrainTypes".equals(qname)) {
handler.start_CannotBuildOnTheseTerrainTypes(attrs);
} else if ("TrackType".equals(qname)) {
handler.start_TrackType(attrs);
} else if ("TerrainType".equals(qname)) {
handler.handle_TerrainType(attrs);
} else if ("Tiles".equals(qname)) {
handler.start_Tiles(attrs);
} else if ("TrackPieceTemplate".equals(qname)) {
handler.start_TrackPieceTemplate(attrs);
} else if ("TrackSet".equals(qname)) {
handler.start_TrackSet(attrs);
}
}
Outgoing Methods (calls):
jfreerails.server.parser.Track_TilesParser.startPrefixMapping
Javadoc:
No Javadoc available
Method code:
public void startPrefixMapping(final java.lang.String prefix,
final java.lang.String uri) throws SAXException {
}
No outgoing methods.
jfreerails.util.ArrayBase.buildArray
Javadoc:
/** * Constructs and returns a simple array containing the same data as held in * a portion of this growable array. This override of the base class method * checks that the portion specified actually has data present before * constructing the returned array. * * @param type * element type for constructed array * @param offset * start offset in array * @param length * number of characters to use * @return array containing a copy of the data */
Method code:
/**
* Constructs and returns a simple array containing the same data as held in
* a portion of this growable array. This override of the base class method
* checks that the portion specified actually has data present before
* constructing the returned array.
*
* @param type
* element type for constructed array
* @param offset
* start offset in array
* @param length
* number of characters to use
* @return array containing a copy of the data
*/
@Override
protected Object buildArray(Class type, int offset, int length) {
if (offset + length <= countPresent) {
return super.buildArray(type, offset, length);
}
throw new ArrayIndexOutOfBoundsException();
}
Outgoing Methods (calls):
jfreerails.util.ArrayBase.clear
Javadoc:
/** * Set the array to the empty state. */
Method code:
/**
* Set the array to the empty state.
*/
public final void clear() {
setSize(0);
}
Outgoing Methods (calls):
jfreerails.util.ArrayBase.getAddIndex
Javadoc:
/** * Gets the array offset for appending a value to those in the array. If the * underlying array is full, it is grown by the appropriate size increment * so that the index value returned is always valid for the array in use by * the time of the return. * * @return index position for added element */
Method code:
/**
* Gets the array offset for appending a value to those in the array. If the
* underlying array is full, it is grown by the appropriate size increment
* so that the index value returned is always valid for the array in use by
* the time of the return.
*
* @return index position for added element
*/
protected final int getAddIndex() {
int index = countPresent++;
if (countPresent > countLimit) {
growArray(countPresent);
}
return index;
}
Outgoing Methods (calls):
jfreerails.util.ArrayBase.getArray
Javadoc:
/** * Get the array for another instance of this class. This is a convenience * method to allow subclasses access to the backing array of other * subclasses. * * @param other * subclass instance to get array from * @return backing array object */
Method code:
/**
* Get the array for another instance of this class. This is a convenience
* method to allow subclasses access to the backing array of other
* subclasses.
*
* @param other
* subclass instance to get array from
* @return backing array object
*/
protected static Object getArray(ArrayBase other) {
return other.getArray();
}
Outgoing Methods (calls):
jfreerails.util.ArrayBase.makeInsertSpace
Javadoc:
/** * Makes room to insert a value at a specified index in the array. * * @param index * index position at which to insert element */
Method code:
/**
* Makes room to insert a value at a specified index in the array.
*
* @param index
* index position at which to insert element
*/
protected void makeInsertSpace(int index) {
if (index >= 0 && index <= countPresent) {
if (++countPresent > countLimit) {
growArray(countPresent);
}
if (index < countPresent - 1) {
Object array = getArray();
System.arraycopy(array, index, array, index + 1, countPresent
- index - 1);
}
} else {
throw new ArrayIndexOutOfBoundsException("Invalid index value");
}
}
Outgoing Methods (calls):
jfreerails.util.ArrayBase.remove
Javadoc:
/** * Remove a range of value from the array. The index positions for values * above the range removed are decreased by the number of values removed. * * @param from * index number of first value to be removed * @param to * index number past last value to be removed */
Method code:
/**
* Remove a range of value from the array. The index positions for values
* above the range removed are decreased by the number of values removed.
*
* @param from
* index number of first value to be removed
* @param to
* index number past last value to be removed
*/
public void remove(int from, int to) {
if (from >= 0 && to <= countPresent && from <= to) {
if (to < countPresent) {
int change = from - to;
Object base = getArray();
System.arraycopy(base, to, base, from, countPresent - to);
discardValues(countPresent + change, countPresent);
countPresent += change;
}
} else {
throw new ArrayIndexOutOfBoundsException("Invalid remove range");
}
}
Outgoing Methods (calls):
jfreerails.util.ArrayBase.setSize
Javadoc:
/** * Sets the number of values currently present in the array. If the new size * is greater than the current size, the added values are initialized to the * default values. If the new size is less than the current size, all values * dropped from the array are discarded. * * @param count * number of values to be set */
Method code:
/**
* Sets the number of values currently present in the array. If the new size
* is greater than the current size, the added values are initialized to the
* default values. If the new size is less than the current size, all values
* dropped from the array are discarded.
*
* @param count
* number of values to be set
*/
public void setSize(int count) {
if (count > countLimit) {
growArray(count);
} else if (count < countPresent) {
discardValues(count, countPresent);
}
countPresent = count;
}
Outgoing Methods (calls):
jfreerails.util.ArrayBase.size
Javadoc:
/** * Get the number of values currently present in the array. * * @return count of values present */
Method code:
/**
* Get the number of values currently present in the array.
*
* @return count of values present
*/
public final int size() {
return countPresent;
}
No outgoing methods.
jfreerails.util.ClassLocater.addSkipPrefix
Javadoc:
/** * Adds a prefix for classes (and packages) to completely ignore, based on * their package + class name. * <p> * For example, "org.apache.log4j". * <P> * The advantage of this method is that you don't have to bother with regex * syntax. Also, it is remembered between calls to getSubclassesOf - so it's * useful if you know you never care about certain packages. * * @param s * prefix of fully qualified class names to ignore */
Method code:
/**
* Adds a prefix for classes (and packages) to completely ignore, based on
* their package + class name.
* <p>
* For example, "org.apache.log4j".
* <P>
* The advantage of this method is that you don't have to bother with regex
* syntax. Also, it is remembered between calls to getSubclassesOf - so it's
* useful if you know you never care about certain packages.
*
* @param s
* prefix of fully qualified class names to ignore
*/
public void addSkipPrefix(String s) {
skipPrefixes.add(s);
}
No outgoing methods.
jfreerails.util.ClassLocater.getSubclassesOf
Javadoc:
/** * Find all subclasses of the given <code>Class</code> or interface by * loading only those classes with names that match the given regular * expression. * <P> * Once all classes have been checked, it will output at WARN a list of all * the classes that were referenced by other classes but are not installed * in the classpath. This can be incredibly useful - it catches situations * where e.g. you thought a class was on the classpath but you put it in the * wrong directory etc. * <P> * It can also be very annoying because java uses dynamic linking so it is * LEGAL for many classes to be missing, just so long as you never use them * at runtime. Because this class tries to use *every* class, it triggers * errors on lots that you don't care about - use addSkipPrefix( class or * package you dont use even though its on the classpath ) and they will be * skipped (i.e. not even examined by this method). * <P> * OR improve your regex so that it is more selective about the packages * where your classes could conceivable be located! * * @param targetType * the superclass of all returned classes. * @param regex * a regular expression that will match with every subclass * @return an array of all subclasses of <code>targetType</code> */
Method code:
/**
* Find all subclasses of the given <code>Class</code> or interface by
* loading only those classes with names that match the given regular
* expression.
* <P>
* Once all classes have been checked, it will output at WARN a list of all
* the classes that were referenced by other classes but are not installed
* in the classpath. This can be incredibly useful - it catches situations
* where e.g. you thought a class was on the classpath but you put it in the
* wrong directory etc.
* <P>
* It can also be very annoying because java uses dynamic linking so it is
* LEGAL for many classes to be missing, just so long as you never use them
* at runtime. Because this class tries to use *every* class, it triggers
* errors on lots that you don't care about - use addSkipPrefix( class or
* package you dont use even though its on the classpath ) and they will be
* skipped (i.e. not even examined by this method).
* <P>
* OR improve your regex so that it is more selective about the packages
* where your classes could conceivable be located!
*
* @param targetType
* the superclass of all returned classes.
* @param regex
* a regular expression that will match with every subclass
* @return an array of all subclasses of <code>targetType</code>
*/
@SuppressWarnings("unchecked")
public Class[] getSubclassesOf(Class targetType, String regex) {
logger.info("Looking for all classes with names matching regex = "
+ regex + " and which are subtypes of " + targetType.getName());
StringBuffer sbSkips = new StringBuffer();
for (Iterator i2 = skipPrefixes.iterator(); i2.hasNext();) {
sbSkips.append(i2.next().toString() + "*");
if (i2.hasNext())
sbSkips.append(", ");
}
logger.info("...unless they match: " + sbSkips.toString());
LinkedList<Class> matches = new LinkedList<Class>();
HashMap<String, LinkedList<String>> missingRequiredClasses = new HashMap<String, LinkedList<String>>();
// maps class name to list of classes that needed it
logger.fine("Creating ClassPath object to do class search...");
ClassPath cp = new ClassPath();
logger.fine("Iterating through all classes in ClassPath...");
for (Iterator iter = cp.getAllClassNames().iterator(); iter.hasNext();) {
String className = (String) iter.next();
boolean skip = false;
for (Iterator i2 = skipPrefixes.iterator(); i2.hasNext();) {
String prefix = (String) i2.next();
if (className.startsWith(prefix)) {
logger.fine("Skipping class = " + className
+ " because it has a prefix of " + prefix);
skip = true;
break;
}
}
if (skip)
continue;
logger.fine("Processing class: " + className);
if (className.matches(regex)
&& !className.equals(targetType.getName())) {
logger
.fine("...matches regex; instantiating and checking type");
Class clazz = null;
try {
clazz = Class.forName(className);
}
/*
* catch (ClassNotFoundException cnfx ) { continue; }
*/
catch (NoClassDefFoundError cnfx) {
/*
* This is ridiculous. Please, everyone, ask sun to add a
* "getMissingClass()" method to NoClassDefFoundError: Sun,
* you have had TEN YEARS to fix this!
*/
if (cnfx.getMessage() == null) {
logger
.log(
Level.WARNING,
"NoClassDefFoundError but Sun didn't fill-in the message; no idea which class it was; ignoring it and moving on",
cnfx);
continue;
}
String missingClassName = cnfx.getMessage().replace('/',
'.');
LinkedList<String> misses = missingRequiredClasses
.get(missingClassName);
if (misses == null) {
misses = new LinkedList<String>();
missingRequiredClasses.put(missingClassName, misses);
}
misses.add(className);
continue;
} catch (UnsatisfiedLinkError cnfx) {
continue;
} catch (Throwable t) {
logger.log(Level.WARNING,
"Unexpected error - REMOVING this class ("
+ className + ") without checking it", t);
continue;
} finally {
if (clazz != null && targetType.isAssignableFrom(clazz)) {
logger
.fine(className
+ " matches and is correct type; adding to results");
matches.add(clazz);
}
}
}
}
if (missingRequiredClasses.size() > 0) {
logger
.warning("The following classes were needed by some of the classes I found, but could not themselves be found."
+ "Check you have the required libraries, that they are on the classpath, and that all JAR's are in your manifest as needed");
logger
.warning("If you don't care about some of the classes that used these missing classes, add the users to the skip list and you will get no errors from them");
for (Iterator<String> iter = missingRequiredClasses.keySet()
.iterator(); iter.hasNext();) {
String className = iter.next();
LinkedList<String> neededBy = missingRequiredClasses
.get(className);
StringBuffer sb = new StringBuffer();
for (Iterator<String> iterator = neededBy.iterator(); iterator
.hasNext();) {
String referencingClass = iterator.next();
sb.append(referencingClass);
if (iterator.hasNext())
sb.append(", ");
}
logger.warning("class: " + className + " was needed by class"
+ (neededBy.size() == 1 ? "" : "es") + ": " + sb);
}
}
logger.info("found " + matches.size() + " classes.");
return matches.toArray(new Class[matches.size()]);
}
Outgoing Methods (calls):
jfreerails.util.ClassLocater.instantiateOneOfEach
Javadoc:
/** * Finds all classes that implement or extend a given class name, and * instantiates precisely one copy of each * * @param className * fully qualified class or interface to find subclasses of, e.g. * "java.lang.String" * @param skipPrefixes * prefixes of fully qualified packages or class names to * completely ignore (i.e. not bother to check), making it * faster, e.g. "java.", "com.sun" * @return instantiated objects */
Method code:
/**
* Finds all classes that implement or extend a given class name, and
* instantiates precisely one copy of each
*
* @param className
* fully qualified class or interface to find subclasses of, e.g.
* "java.lang.String"
* @param skipPrefixes
* prefixes of fully qualified packages or class names to
* completely ignore (i.e. not bother to check), making it
* faster, e.g. "java.", "com.sun"
* @return instantiated objects
*/
public static List instantiateOneOfEach(String className,
String[] skipPrefixes) {
Class[] classes = null;
LinkedList<Object> instances = new LinkedList<Object>();
try {
ClassLocater locater = new ClassLocater();
for (int i = 0; i < skipPrefixes.length; i++) {
locater.addSkipPrefix(skipPrefixes[i]);
}
classes = locater.getSubclassesOf(Class.forName(className));
logger.info("Found " + classes.length + " classes that implement "
+ className + "...");
if (logger.getLevel().equals(Level.FINE))
for (int i = 0; i < classes.length; i++) {
logger.fine("Found " + classes[i].getName()
+ " that implements " + className + "...");
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Attempting to find " + className
+ " implementers", e);
}
// Iterate through all, instantiating them
logger.fine("Instantiating each class");
for (int i = 0; i < classes.length; i++) {
try {
Object o = classes[i].newInstance();
instances.add(o);
} catch (Throwable e) {
logger.log(Level.SEVERE, "Failed to process: "
+ classes[i].getName(), e);
}
}
return instances;
}
Outgoing Methods (calls):
jfreerails.util.ClassPath.convertToClass
Javadoc:
/** * @param classFile * a class file listed on the classpath itself. */
Method code:
/**
* @param classFile
* a class file listed on the classpath itself.
*/
protected String convertToClass(File classFile) {
return getClassNameFrom(classFile.getName());
}
Outgoing Methods (calls):
jfreerails.util.ClassPath.findPathElementsInJar
Javadoc:
/** * Finds all path elements in the supplied JAR and returns them as a list * * @param man * the manifest of the given jar * @param jar * the jar associated with the given manifest. */
Method code:
/**
* Finds all path elements in the supplied JAR and returns them as a list
*
* @param man
* the manifest of the given jar
* @param jar
* the jar associated with the given manifest.
*/
protected LinkedList<String> findPathElementsInJar(Manifest man,
JarFile jar, File jarFile) {
LinkedList<String> result = new LinkedList<String>();
Attributes atts = man.getMainAttributes();
Set keys = atts.keySet();
Iterator i = keys.iterator();
while (i.hasNext()) {
Object key = i.next();
String value = (String) atts.get(key);
logger.fine(jar.getName() + " " + key + ": " + value);
if (key.toString().equals("Class-Path")) {
logger.info("scanning " + jar.getName()
+ "'s manifest classpath: " + value);
StringTokenizer toke = new StringTokenizer(value);
while (toke.hasMoreTokens()) {
String element = toke.nextToken();
if (jarFile.getParent() == null)
result.add(element);
else {
result.add(jarFile.getParent() + File.separator
+ element);
}
}
}
}
return result;
}
No outgoing methods.
jfreerails.util.ClassPath.getAllClassNames
Javadoc:
No Javadoc available
Method code:
public List getAllClassNames() {
String path = null;
pathElementsThatHaveAlreadyBeenProcessed = new LinkedList<String>();
jarsThatHAveAlreadyBeenProcessed = new LinkedList<File>();
LinkedList<String> pendingClassPathElements = new LinkedList<String>();
LinkedList<String> processedClassPathElements = new LinkedList<String>();
try {
path = System.getProperty("java.class.path");
} catch (Exception x) {
x.printStackTrace();
}
logger.info("scanning classpath: " + path);
StringTokenizer toke = new StringTokenizer(path, File.pathSeparator);
while (toke.hasMoreTokens()) {
String pathElement = toke.nextToken();
pendingClassPathElements.add(pathElement);
}
for (Iterator<String> iter = pendingClassPathElements.iterator(); iter
.hasNext();) {
String pathElement = iter.next();
LinkedList<String> processPendingElement = processPendingElement(pathElement);
processedClassPathElements.addAll(processPendingElement);
}
return processedClassPathElements;
}
Outgoing Methods (calls):
jfreerails.util.ClassPath.getClassNameFrom
Javadoc:
/** * replace ANY slashes with dots and remove the .class at the end of the * file name. * * @param entryName * a file name relative to the classpath. A class of package org * found in directory bin would be passed into this method as * "org/MyClass.class" * @return a fully qualified Class name. */
Method code:
/**
* replace ANY slashes with dots and remove the .class at the end of the
* file name.
*
* @param entryName
* a file name relative to the classpath. A class of package org
* found in directory bin would be passed into this method as
* "org/MyClass.class"
* @return a fully qualified Class name.
*/
private String getClassNameFrom(String entryName) {
String foo = entryName.replace('/', '.');
foo = foo.replace('\\', '.');
return foo.substring(0, foo.lastIndexOf('.'));
}
No outgoing methods.
jfreerails.util.ClassPath.getDirectoryContents
Javadoc:
/** * This method takes a top level classpath dir i.e. 'classes' or bin * * @param dir */
Method code:
/**
* This method takes a top level classpath dir i.e. 'classes' or bin
*
* @param dir
*/
protected LinkedList<String> getDirectoryContents(File dir) {
LinkedList<String> result = new LinkedList<String>();
// drill through contained dirs ... this is expected to be the
// 'classes' or 'bin' dir
File files[] = dir.listFiles();
if (null == files) {
logger.info("dir.listFiles() returned null for " + dir);
return result;
}
for (int i = 0; i < files.length; ++i) {
File f = files[i];
if (f.isDirectory()) {
result.addAll(getDirectoryContents("", f));
} else {
if (f.getName().endsWith(".class"))
result.add(convertToClass(f));
}
}
return result;
}
Outgoing Methods (calls):
jfreerails.util.ClassPath.getZipContents
Javadoc:
/** * Adds all class names found in the zip mentioned * * @param zipFile */
Method code:
/**
* Adds all class names found in the zip mentioned
*
* @param zipFile
*/
protected LinkedList<String> getZipContents(File zipFile) {
LinkedList<String> result = new LinkedList<String>();
ZipFile zip = null;
try {
zip = new JarFile(zipFile);
} catch (IOException iox) {
}
if (zip != null) {
Enumeration e = zip.entries();
while (e.hasMoreElements()) {
ZipEntry entry = (ZipEntry) e.nextElement();
if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
String className = getClassNameFrom(entry.getName());
result.add(className);
}
}
}
return result;
}
Outgoing Methods (calls):
jfreerails.util.ClassPath.processPendingElement
Javadoc:
/** * Clones the supplied list, then goes through it processing every element. * */
Method code:
/**
* Clones the supplied list, then goes through it processing every element.
*
*/
protected LinkedList<String> processPendingElement(String pathElement) {
LinkedList<String> discoveredClasses = new LinkedList<String>();
File elementFile = new File(pathElement);
String elementName = elementFile.getAbsolutePath();
// do NOT process dupes
if (pathElementsThatHaveAlreadyBeenProcessed.contains(elementName))
return discoveredClasses;
try {
if (elementName.endsWith(".jar")) {
JarFile jar = null;
Manifest man = null;
jar = new JarFile(elementFile);
man = jar.getManifest();
// Find any nested path elements inside the JAR's own private
// class-path...
if (!(jarsThatHAveAlreadyBeenProcessed.contains(elementFile))) {
if (man != null) {
logger.fine("Jarfile = " + elementFile
+ " was not in jarsalreadydone (size = "
+ jarsThatHAveAlreadyBeenProcessed.size());
jarsThatHAveAlreadyBeenProcessed.add(elementFile);
List extraPathElements = findPathElementsInJar(man,
jar, elementFile);
logger.info("...[" + elementFile + "] contained "
+ extraPathElements.size()
+ " additional path elements");
for (Iterator iter = extraPathElements.iterator(); iter
.hasNext();) {
String element = (String) iter.next();
discoveredClasses
.addAll(processPendingElement(element));
}
}
// ...and add all the direct-listed classes that were in the
// JAR
Enumeration e = jar.entries();
while (e.hasMoreElements()) {
JarEntry entry = (JarEntry) e.nextElement();
if (!entry.isDirectory()
&& entry.getName().endsWith(".class")) {
String className = getClassNameFrom(entry.getName());
discoveredClasses.add(className);
}
}
}
} else if (elementName.endsWith(".zip")) {
discoveredClasses.addAll(getZipContents(elementFile));
} else if (elementName.endsWith(".class")) {
String className = convertToClass(elementFile);
discoveredClasses.add(className);
} else {
discoveredClasses.addAll(getDirectoryContents(elementFile));
}
// Mark this element as having been processed, and do NOT process
// dupes
pathElementsThatHaveAlreadyBeenProcessed.add(elementName);
} catch (Exception e) {
e.printStackTrace();
}
return discoveredClasses;
}
Outgoing Methods (calls):
jfreerails.util.CompressedInputStream.available
Javadoc:
No Javadoc available
Method code:
@Override
public int available() throws IOException {
if (maxReadIndex - readIndex == 0 && super.in.available() > 0
&& !readNextBuffer()) {
return -1;
}
return maxReadIndex - readIndex;
}
Outgoing Methods (calls):
jfreerails.util.CompressedInputStream.markSupported
Javadoc:
No Javadoc available
Method code:
@Override
public boolean markSupported() {
return false;
}
No outgoing methods.
jfreerails.util.CompressedInputStream.read
Javadoc:
No Javadoc available
Method code:
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
Outgoing Methods (calls):
jfreerails.util.CompressedInputStream.readNextBuffer
Javadoc:
No Javadoc available
Method code:
private boolean readNextBuffer() throws IOException {
byte compressionFlag = -1;
compressionFlag = (byte) super.in.read();
if (compressionFlag == -1) {
return false;
}
maxReadIndex = super.in.read() & 0xff;
maxReadIndex = maxReadIndex << 8 | super.in.read() & 0xff;
maxReadIndex = maxReadIndex << 8 | super.in.read() & 0xff;
maxReadIndex = maxReadIndex << 8 | super.in.read() & 0xff;
if (buffer.length < maxReadIndex) {
buffer = new byte[maxReadIndex + 40960];
}
if (compressionFlag == 1) {
int compSize = super.in.read() & 0xff;
compSize = compSize << 8 | super.in.read() & 0xff;
compSize = compSize << 8 | super.in.read() & 0xff;
compSize = compSize << 8 | super.in.read() & 0xff;
if (compBuffer.length < compSize) {
compBuffer = new byte[compSize + 40960];
}
for (int read = 0; read < compSize; read += super.in.read(
compBuffer, read, compSize - read)) {
}
inflater.reset();
inflater.setInput(compBuffer, 0, compSize);
try {
inflater.inflate(buffer);
} catch (DataFormatException ex) {
throw new IOException("Data format exception");
}
} else if (compressionFlag == 0) {
for (int read = 0; read < maxReadIndex; read += super.in.read(
buffer, read, maxReadIndex - read)) {
}
}
readIndex = 0;
return true;
}
No outgoing methods.
jfreerails.util.CompressedOutputStream.flush
Javadoc:
No Javadoc available
Method code:
@Override
public void flush() throws IOException {
int compSize = 0;
boolean sendCompressed;
if (writeIndex > 150) {
deflater.reset();
deflater.setInput(buffer, 0, writeIndex);
deflater.finish();
if (compBuffer.length < writeIndex * 2 + 40960) {
compBuffer = new byte[writeIndex * 2 + 40960];
}
compSize = deflater.deflate(compBuffer);
if (compSize <= 0) {
throw new IOException("Compression exception");
}
sendCompressed = compSize < writeIndex;
} else {
sendCompressed = false;
}
if (sendCompressed) {
super.out.write(1);
super.out.write(writeIndex >> 24 & 0xff);
super.out.write(writeIndex >> 16 & 0xff);
super.out.write(writeIndex >> 8 & 0xff);
super.out.write(writeIndex & 0xff);
super.out.write(compSize >> 24 & 0xff);
super.out.write(compSize >> 16 & 0xff);
super.out.write(compSize >> 8 & 0xff);
super.out.write(compSize & 0xff);
super.out.write(compBuffer, 0, compSize);
super.out.flush();
writeIndex = 0;
} else if (writeIndex > 0) {
super.out.write(0);
super.out.write(writeIndex >> 24 & 0xff);
super.out.write(writeIndex >> 16 & 0xff);
super.out.write(writeIndex >> 8 & 0xff);
super.out.write(writeIndex & 0xff);
super.out.write(buffer, 0, writeIndex);
super.out.flush();
writeIndex = 0;
}
}
No outgoing methods.
jfreerails.util.CompressedOutputStream.write
Javadoc:
No Javadoc available
Method code:
@Override
public void write(int b) throws IOException {
if (writeIndex >= buffer.length * 0.80000000000000004D) {
flush();
}
buffer[writeIndex++] = (byte) b;
}
Outgoing Methods (calls):
jfreerails.util.FlowRateInputStream.close
Javadoc:
No Javadoc available
Method code:
@Override
public void close() throws IOException {
closeRequested = true;
super.close();
do {
try {
Thread.currentThread();
Thread.sleep(50L);
} catch (InterruptedException interruptedexception) {
}
} while (running);
logger.info(String.valueOf(String.valueOf((new StringBuffer("Stream "))
.append(streamName).append(": Open duration = ").append(
(System.currentTimeMillis() - openTimeMillis) / 1000D)
.append(", Byte received = ").append(totalByteReceived).append(
" (").append((int) (totalByteReceived / 1024D)).append(
" Ko), overall flow rate = ").append(overallRate())
.append(" Ko/s"))));
}
Outgoing Methods (calls):
jfreerails.util.FlowRateInputStream.currentRate
Javadoc:
No Javadoc available
Method code:
public int currentRate() {
return (int) (byteReceivedCumul / 1024D / (nbUsed * (measureInterval / 1000D)));
}
No outgoing methods.
jfreerails.util.FlowRateInputStream.currentRateString
Javadoc:
No Javadoc available
Method code:
public String currentRateString() {
double d = (byteReceivedCumul / 1024D / (nbUsed * (measureInterval / 1000D)));
return decimalFormat.format(d);
}
No outgoing methods.
jfreerails.util.FlowRateInputStream.overallRate
Javadoc:
No Javadoc available
Method code:
public int overallRate() {
return (int) (totalByteReceived / 1024D / ((System.currentTimeMillis() - openTimeMillis) / 1000D));
}
No outgoing methods.
jfreerails.util.FlowRateInputStream.read
Javadoc:
No Javadoc available
Method code:
@Override
public int read(byte[] b) throws IOException {
int r = super.in.read(b);
totalByteReceived += r;
return r;
}
No outgoing methods.
jfreerails.util.FlowRateInputStream.run
Javadoc:
No Javadoc available
Method code:
public void run() {
if (running || measureInterval == 0x7fffffffffffffffL) {
return;
}
running = true;
try {
do {
try {
Thread.currentThread();
Thread.sleep(measureInterval);
} catch (InterruptedException interruptedexception) {
}
if (!closeRequested) {
long totalByteReceivedCopy = totalByteReceived;
long byteSentThisTime = totalByteReceivedCopy
- previousTotalByteReceived;
previousTotalByteReceived = totalByteReceivedCopy;
byteReceivedCumul -= byteReceived[nextFree];
byteReceived[nextFree] = byteSentThisTime;
byteReceivedCumul += byteSentThisTime;
nextFree = (nextFree + 1) % byteReceived.length;
nbUsed = Math.min(byteReceived.length, nbUsed + 1);
if (showTrace) {
logger
.info(String
.valueOf(String
.valueOf((new StringBuffer(
"Stream "))
.append(streamName)
.append(
": Open duration = ")
.append(
(System
.currentTimeMillis() - openTimeMillis) / 1000D)
.append(
", Byte sent = ")
.append(
totalByteReceived)
.append(" (")
.append(
(int) (totalByteReceived / 1024D))
.append(
" Ko), current flow rate = ")
.append(
currentRateString())
.append(" Ko/s"))));
}
}
} while (!closeRequested);
} finally {
running = false;
}
}
Outgoing Methods (calls):
jfreerails.util.FlowRateOutputStream.close
Javadoc:
No Javadoc available
Method code:
@Override
public void close() throws IOException {
closeRequested = true;
super.close();
do {
try {
Thread.currentThread();
Thread.sleep(50L);
} catch (InterruptedException interruptedexception) {
}
} while (running);
logger.info(String.valueOf(String.valueOf((new StringBuffer("Stream "))
.append(streamName).append(": Open duration = ").append(
(System.currentTimeMillis() - openTimeMillis) / 1000D)
.append(", Byte sent = ").append(totalByteSent).append(" (")
.append((int) (totalByteSent / 1024D)).append(
" Ko), overall flow rate = ").append(
overallRateString()).append(" Ko/s"))));
}
Outgoing Methods (calls):
jfreerails.util.FlowRateOutputStream.currentRate
Javadoc:
No Javadoc available
Method code:
public int currentRate() throws IOException {
return (int) (byteSentCumul / 1024D / (nbUsed * (measureInterval / 1000D)));
}
No outgoing methods.
jfreerails.util.FlowRateOutputStream.currentRateString
Javadoc:
No Javadoc available
Method code:
public String currentRateString() {
double d = (byteSentCumul / 1024D / (nbUsed * (measureInterval / 1000D)));
return decimalFormat.format(d);
}
No outgoing methods.
jfreerails.util.FlowRateOutputStream.overallRate
Javadoc:
No Javadoc available
Method code:
public int overallRate() throws IOException {
return (int) (totalByteSent / 1024D / ((System.currentTimeMillis() - openTimeMillis) / 1000D));
}
No outgoing methods.
jfreerails.util.FlowRateOutputStream.overallRateString
Javadoc:
No Javadoc available
Method code:
public String overallRateString() throws IOException {
double d = totalByteSent / 1024D
/ ((System.currentTimeMillis() - openTimeMillis) / 1000D);
return decimalFormat.format(d);
}
No outgoing methods.
jfreerails.util.FlowRateOutputStream.run
Javadoc:
No Javadoc available
Method code:
public void run() {
if (running) {
throw new Error("Starting thread task on an already-started object");
}
if (measureInterval == 0x7fffffffffffffffL) {
return;
}
running = true;
try {
do {
try {
Thread.currentThread();
Thread.sleep(measureInterval);
} catch (InterruptedException interruptedexception) {
}
if (!closeRequested) {
long totalByteSentCopy = totalByteSent;
long byteSentThisTime = totalByteSentCopy
- previousTotalByteSent;
previousTotalByteSent = totalByteSentCopy;
byteSentCumul -= byteSent[nextFree];
byteSent[nextFree] = byteSentThisTime;
byteSentCumul += byteSentThisTime;
nextFree = (nextFree + 1) % byteSent.length;
nbUsed = Math.min(byteSent.length, nbUsed + 1);
if (showTrace) {
logger
.info(String
.valueOf(String
.valueOf((new StringBuffer(
"Stream "))
.append(streamName)
.append(
": Open duration = ")
.append(
(System
.currentTimeMillis() - openTimeMillis) / 1000D)
.append(
", Byte sent = ")
.append(totalByteSent)
.append(" (")
.append(
(int) (totalByteSent / 1024D))
.append(
" Ko), current flow rate = ")
.append(
currentRateString())
.append(" Ko/s"))));
}
}
} while (!closeRequested);
// } catch (IOException ioexception) {
} finally {
running = false;
}
}
Outgoing Methods (calls):
jfreerails.util.FlowRateOutputStream.write
Javadoc:
No Javadoc available
Method code:
@Override
public void write(int b) throws IOException {
super.out.write(b);
totalByteSent++;
}
No outgoing methods.
jfreerails.util.FreerailsIntIterator.hasNextInt
Javadoc:
No Javadoc available
Method code:
boolean hasNextInt();
No outgoing methods.
jfreerails.util.FreerailsIntIterator.nextInt
Javadoc:
No Javadoc available
Method code:
int nextInt();
No outgoing methods.
jfreerails.util.FreerailsProgressMonitor.finished
Javadoc:
No Javadoc available
Method code:
void finished();
No outgoing methods.
jfreerails.util.FreerailsProgressMonitor.nextStep
Javadoc:
No Javadoc available
Method code:
void nextStep(int max);
No outgoing methods.
jfreerails.util.FreerailsProgressMonitor.setValue
Javadoc:
No Javadoc available
Method code:
void setValue(int i);
No outgoing methods.
jfreerails.util.GameModel.update
Javadoc:
No Javadoc available
Method code:
void update();
No outgoing methods.
jfreerails.util.GrowableBase.buildArray
Javadoc:
/** * Constructs and returns a simple array containing the same data as held in * a portion of this growable array. * * @param type * element type for constructed array * @param offset * start offset in array * @param length * number of characters to use * @return array containing a copy of the data */
Method code:
/**
* Constructs and returns a simple array containing the same data as held in
* a portion of this growable array.
*
* @param type
* element type for constructed array
* @param offset
* start offset in array
* @param length
* number of characters to use
* @return array containing a copy of the data
*/
protected Object buildArray(Class type, int offset, int length) {
Object copy = Array.newInstance(type, length);
System.arraycopy(getArray(), offset, copy, 0, length);
return copy;
}
Outgoing Methods (calls):
jfreerails.util.GrowableBase.discardValues
Javadoc:
/** * Discards values for a range of indices in the array. Checks if the values * stored in the array are object references, and if so clears them. If the * values are primitives, this method does nothing. * * @param from * index of first value to be discarded * @param to * index past last value to be discarded */
Method code:
/**
* Discards values for a range of indices in the array. Checks if the values
* stored in the array are object references, and if so clears them. If the
* values are primitives, this method does nothing.
*
* @param from
* index of first value to be discarded
* @param to
* index past last value to be discarded
*/
protected void discardValues(int from, int to) {
Object values = getArray();
if (!values.getClass().getComponentType().isPrimitive()) {
Object[] objects = (Object[]) values;
for (int i = from; i < to; i++) {
objects[i] = null;
}
}
}
Outgoing Methods (calls):
jfreerails.util.GrowableBase.ensureCapacity
Javadoc:
/** * Ensure that the array has the capacity for at least the specified number * of values. * * @param min * minimum capacity to be guaranteed */
Method code:
/**
* Ensure that the array has the capacity for at least the specified number
* of values.
*
* @param min
* minimum capacity to be guaranteed
*/
public final void ensureCapacity(int min) {
if (min > countLimit) {
growArray(min);
}
}
Outgoing Methods (calls):
jfreerails.util.GrowableBase.getArray
Javadoc:
/** * Get the backing array. This method is used by the type-agnostic base * class code to access the array used for type-specific storage by the * child class. * * @return backing array object */
Method code:
/**
* Get the backing array. This method is used by the type-agnostic base
* class code to access the array used for type-specific storage by the
* child class.
*
* @return backing array object
*/
protected abstract Object getArray();
No outgoing methods.
jfreerails.util.GrowableBase.growArray
Javadoc:
/** * Increase the size of the array to at least a specified size. The array * will normally be at least doubled in size, but if a maximum size * increment was specified in the constructor and the value is less than the * current size of the array, the maximum increment will be used instead. If * the requested size requires more than the default growth, the requested * size overrides the normal growth and determines the size of the * replacement array. * * @param required * new minimum size required */
Method code:
/**
* Increase the size of the array to at least a specified size. The array
* will normally be at least doubled in size, but if a maximum size
* increment was specified in the constructor and the value is less than the
* current size of the array, the maximum increment will be used instead. If
* the requested size requires more than the default growth, the requested
* size overrides the normal growth and determines the size of the
* replacement array.
*
* @param required
* new minimum size required
*/
protected void growArray(int required) {
Object base = getArray();
int size = Math.max(required, countLimit
+ Math.min(countLimit, maximumGrowth));
Class type = base.getClass().getComponentType();
Object grown = Array.newInstance(type, size);
resizeCopy(base, grown);
countLimit = size;
setArray(grown);
}
Outgoing Methods (calls):
jfreerails.util.GrowableBase.resizeCopy
Javadoc:
/** * Copy data after array resize. This default implementation just copies the * entire contents of the old array to the start of the new array. It should * be overridden in cases where data needs to be rearranged in the array * after a resize. * * @param base * original array containing data * @param grown * resized array for data */
Method code:
/**
* Copy data after array resize. This default implementation just copies the
* entire contents of the old array to the start of the new array. It should
* be overridden in cases where data needs to be rearranged in the array
* after a resize.
*
* @param base
* original array containing data
* @param grown
* resized array for data
*/
protected void resizeCopy(Object base, Object grown) {
System.arraycopy(base, 0, grown, 0, Array.getLength(base));
}
No outgoing methods.
jfreerails.util.GrowableBase.setArray
Javadoc:
/** * Set the backing array. This method is used by the type-agnostic base * class code to set the array used for type-specific storage by the child * class. * */
Method code:
/**
* Set the backing array. This method is used by the type-agnostic base
* class code to set the array used for type-specific storage by the child
* class.
*
*/
protected abstract void setArray(Object array);
No outgoing methods.
jfreerails.util.IntArray.add
Javadoc:
/** * Add a value at a specified index in the array. * * @param index * index position at which to insert element * @param value * value to be inserted into array */
Method code:
/**
* Add a value at a specified index in the array.
*
* @param index
* index position at which to insert element
* @param value
* value to be inserted into array
*/
public void add(int index, int value) {
makeInsertSpace(index);
baseArray[index] = value;
}
Outgoing Methods (calls):
jfreerails.util.IntArray.get
Javadoc:
/** * Retrieve the value present at an index position in the array. * * @param index * index position for value to be retrieved * @return value from position in the array */
Method code:
/**
* Retrieve the value present at an index position in the array.
*
* @param index
* index position for value to be retrieved
* @return value from position in the array
*/
public final int get(int index) {
if (index < countPresent) {
return baseArray[index];
}
throw new ArrayIndexOutOfBoundsException("Invalid index value");
}
No outgoing methods.
jfreerails.util.IntArray.getArray
Javadoc:
/** * Get the backing array. This method is used by the type-agnostic base * class code to access the array used for type-specific storage. * * @return backing array object */
Method code:
/**
* Get the backing array. This method is used by the type-agnostic base
* class code to access the array used for type-specific storage.
*
* @return backing array object
*/
@Override
protected final Object getArray() {
return baseArray;
}
No outgoing methods.
jfreerails.util.IntArray.set
Javadoc:
/** * Set the value at an index position in the array. * * @param index * index position to be set * @param value * value to be set */
Method code:
/**
* Set the value at an index position in the array.
*
* @param index
* index position to be set
* @param value
* value to be set
*/
public final void set(int index, int value) {
if (index < countPresent) {
baseArray[index] = value;
} else {
throw new ArrayIndexOutOfBoundsException("Invalid index value");
}
}
No outgoing methods.
jfreerails.util.IntArray.setArray
Javadoc:
/** * Set the backing array. This method is used by the type-agnostic base * class code to set the array used for type-specific storage. * */
Method code:
/**
* Set the backing array. This method is used by the type-agnostic base
* class code to set the array used for type-specific storage.
*
*/
@Override
protected final void setArray(Object array) {
baseArray = (int[]) array;
}
No outgoing methods.
jfreerails.util.IntArray.toArray
Javadoc:
/** * Constructs and returns a simple array containing the same data as held in * a portion of this growable array. * * @param offset * start offset in array * @param length * number of characters to use * @return array containing a copy of the data */
Method code:
/**
* Constructs and returns a simple array containing the same data as held in
* a portion of this growable array.
*
* @param offset
* start offset in array
* @param length
* number of characters to use
* @return array containing a copy of the data
*/
public int[] toArray(int offset, int length) {
return (int[]) buildArray(int.class, offset, length);
}
Outgoing Methods (calls):
jfreerails.util.LRUCache.clear
Javadoc:
/** * Clears the cache. */
Method code:
/**
* Clears the cache.
*/
public synchronized void clear() {
map.clear();
}
No outgoing methods.
jfreerails.util.LRUCache.get
Javadoc:
/** * Retrieves an entry from the cache.<br> * The retrieved entry becomes the MRU (most recently used) entry. * * @param key * the key whose associated value is to be returned. * @return the value associated to this key, or null if no value with this * key exists in the cache. */
Method code:
/**
* Retrieves an entry from the cache.<br>
* The retrieved entry becomes the MRU (most recently used) entry.
*
* @param key
* the key whose associated value is to be returned.
* @return the value associated to this key, or null if no value with this
* key exists in the cache.
*/
public synchronized V get(K key) {
return map.get(key);
}
No outgoing methods.
jfreerails.util.LRUCache.getAll
Javadoc:
/** * Returns a <code>Collection</code> that contains a copy of all cache * entries. * * @return a <code>Collection</code> with a copy of the cache content. */
Method code:
/**
* Returns a <code>Collection</code> that contains a copy of all cache
* entries.
*
* @return a <code>Collection</code> with a copy of the cache content.
*/
public synchronized Collection<Map.Entry<K, V>> getAll() {
return new ArrayList<Map.Entry<K, V>>(map.entrySet());
}
No outgoing methods.
jfreerails.util.LRUCache.put
Javadoc:
/** * Adds an entry to this cache. If the cache is full, the LRU (least * recently used) entry is dropped. * * @param key * the key with which the specified value is to be associated. * @param value * a value to be associated with the specified key. */
Method code:
/**
* Adds an entry to this cache. If the cache is full, the LRU (least
* recently used) entry is dropped.
*
* @param key
* the key with which the specified value is to be associated.
* @param value
* a value to be associated with the specified key.
*/
public synchronized void put(K key, V value) {
map.put(key, value);
}
No outgoing methods.
jfreerails.util.LRUCache.usedEntries
Javadoc:
/** * Returns the number of used entries in the cache. * * @return the number of entries currently in the cache. */
Method code:
/**
* Returns the number of used entries in the cache.
*
* @return the number of entries currently in the cache.
*/
public synchronized int usedEntries() {
return map.size();
}
No outgoing methods.
jfreerails.util.List1D.add
Javadoc:
No Javadoc available
Method code:
int add(T element);
No outgoing methods.
jfreerails.util.List1D.get
Javadoc:
No Javadoc available
Method code:
T get(int i);
No outgoing methods.
jfreerails.util.List1D.removeLast
Javadoc:
No Javadoc available
Method code:
T removeLast();
No outgoing methods.
jfreerails.util.List1D.set
Javadoc:
No Javadoc available
Method code:
void set(int i, T element);
No outgoing methods.
jfreerails.util.List1D.size
Javadoc:
No Javadoc available
Method code:
int size();
No outgoing methods.
jfreerails.util.List1DDiff.add
Javadoc:
No Javadoc available
Method code:
public int add(T element) {
return super.addElement(element);
}
Outgoing Methods (calls):
jfreerails.util.List1DDiff.get
Javadoc:
No Javadoc available
Method code:
public T get(int i) {
return get(new int[] { i });
}
Outgoing Methods (calls):
jfreerails.util.List1DDiff.getUnderlyingList
Javadoc:
No Javadoc available
Method code:
@Override
Object getUnderlyingList() {
return underlyingList;
}
No outgoing methods.
jfreerails.util.List1DDiff.getUnderlyingSize
Javadoc:
No Javadoc available
Method code:
@Override
int getUnderlyingSize(int... dim) {
if (dim.length != 0)
throw new IllegalArgumentException(String.valueOf(dim.length));
return underlyingList.size();
}
Outgoing Methods (calls):
jfreerails.util.List1DDiff.removeLast
Javadoc:
No Javadoc available
Method code:
public T removeLast() {
return super.removeLast();
}
Outgoing Methods (calls):
jfreerails.util.List1DDiff.set
Javadoc:
No Javadoc available
Method code:
public void set(int i, T element) {
super.set(element, i);
}
Outgoing Methods (calls):
jfreerails.util.List1DDiff.size
Javadoc:
No Javadoc available
Method code:
public int size() {
return super.size(new int[0]);
}
Outgoing Methods (calls):
jfreerails.util.List1DDiff.uGet
Javadoc:
No Javadoc available
Method code:
@Override
T uGet(int... i) {
if (i.length != 1)
throw new IllegalArgumentException();
return underlyingList.get(i[0]);
}
Outgoing Methods (calls):
jfreerails.util.List1DDiffsTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
list = new List1DImpl<Object>();
map = new TreeMap<ListKey, Object>();
diffs = new List1DDiff<Object>(map, list, test.test);
}
No outgoing methods.
jfreerails.util.List1DDiffsTest.testAdd
Javadoc:
No Javadoc available
Method code:
public void testAdd(){
Player player0 = new Player("player0", 0);
Player player1 = new Player("player1", 1);
int i = diffs.add(player0);
assertEquals(0, i);
assertEquals(1, diffs.size());
assertEquals(player0, diffs.get(0));
i = diffs.add(player1);
assertEquals(1, i);
assertEquals(2, diffs.size());
assertEquals(player1, diffs.get(1));
}
Outgoing Methods (calls):
jfreerails.util.List1DDiffsTest.testAddAndRemove
Javadoc:
No Javadoc available
Method code:
public void testAddAndRemove(){
list.add(String.valueOf(1));
assertEquals( String.valueOf(1), diffs.get(0));
int i = diffs.add(String.valueOf(2));
assertEquals(1, i);
assertEquals( String.valueOf(1), diffs.get(0));
assertEquals(diffs.get(1), String.valueOf(2));
assertEquals(2, diffs.size());
assertEquals(2, map.size());
Object removed = diffs.removeLast();
assertEquals(String.valueOf(2), removed);
assertEquals(1, diffs.size());
assertEquals(0, map.size());
removed = diffs.removeLast();
assertEquals(String.valueOf(1), removed);
assertEquals(0, diffs.size());
assertEquals(1, map.size());
}
Outgoing Methods (calls):
jfreerails.util.List1DDiffsTest.testAddAndRemove2
Javadoc:
No Javadoc available
Method code:
public void testAddAndRemove2(){
list.add(String.valueOf(1));
list.add(String.valueOf(1));
list.add(String.valueOf(1));
diffs.removeLast();
diffs.removeLast();
assertEquals(1, diffs.size());
assertEquals(1, map.size());
diffs.add(String.valueOf(2));
diffs.add(String.valueOf(2));
diffs.add(String.valueOf(2));
diffs.add(String.valueOf(2));
assertEquals(5, diffs.size());
assertEquals("4 elements + end=5", 5, map.size());
assertEquals(String.valueOf(1), diffs.get(0));
assertEquals(String.valueOf(2), diffs.get(1));
assertEquals(String.valueOf(2), diffs.get(2));
assertEquals(String.valueOf(2), diffs.get(3));
assertEquals(String.valueOf(2), diffs.get(3));
diffs.set(String.valueOf(3), 2);
assertEquals(5, diffs.size());
assertEquals(5, map.size());
assertEquals(String.valueOf(3), diffs.get(2));
diffs.set(String.valueOf(4), 4);
assertEquals(String.valueOf(4), diffs.get(4));
diffs.removeLast();
diffs.removeLast();
diffs.removeLast();
diffs.removeLast();
assertEquals(1, diffs.size());
assertEquals("fork=1", 1, map.size());
}
Outgoing Methods (calls):
jfreerails.util.List1DDiffsTest.testChangingValues
Javadoc:
No Javadoc available
Method code:
public void testChangingValues(){
list.add(String.valueOf(1));
assertEquals(diffs.get(0), String.valueOf(1));
assertEquals(diffs.size(), list.size());
diffs.set(String.valueOf(2), 0);
assertEquals(diffs.get(0), String.valueOf(2));
assertEquals(1, map.size());
diffs.set(String.valueOf(1),0);
assertEquals(0, map.size());
}
Outgoing Methods (calls):
jfreerails.util.List1DDiffsTest.testSortedMap
Javadoc:
No Javadoc available
Method code:
public void testSortedMap(){
ListKey elementKey1 = new ListKey(ListKey.Type.Element, test.test, 0);
ListKey elementKey2 = new ListKey(ListKey.Type.Element, test.test, 1);
ListKey elementKey3 = new ListKey(ListKey.Type.Element, test.test, 0);
map.put(elementKey1, String.valueOf(1));
assertFalse(map.containsKey(elementKey2));
assertTrue(map.containsKey(elementKey1));
assertTrue(map.containsKey(elementKey3));
}
No outgoing methods.
jfreerails.util.List1DImpl.add
Javadoc:
No Javadoc available
Method code:
public int add(T element) {
elementData.add(element);
return elementData.size() - 1;
}
No outgoing methods.
jfreerails.util.List1DImpl.get
Javadoc:
No Javadoc available
Method code:
public T get(int i) {
return elementData.get(i);
}
No outgoing methods.
jfreerails.util.List1DImpl.removeLast
Javadoc:
No Javadoc available
Method code:
public T removeLast() {
int last = elementData.size() - 1;
return elementData.remove(last);
}
No outgoing methods.
jfreerails.util.List1DImpl.set
Javadoc:
No Javadoc available
Method code:
public void set(int i, T element) {
elementData.set(i, element);
}
No outgoing methods.
jfreerails.util.List1DImpl.size
Javadoc:
No Javadoc available
Method code:
public int size() {
return elementData.size();
}
No outgoing methods.
jfreerails.util.List2D.addD1
Javadoc:
No Javadoc available
Method code:
int addD1();
No outgoing methods.
jfreerails.util.List2D.addD2
Javadoc:
No Javadoc available
Method code:
int addD2(int d1, T element);
No outgoing methods.
jfreerails.util.List2D.get
Javadoc:
No Javadoc available
Method code:
T get(int d1, int d2);
No outgoing methods.
jfreerails.util.List2D.removeLastD1
Javadoc:
No Javadoc available
Method code:
int removeLastD1();
No outgoing methods.
jfreerails.util.List2D.removeLastD2
Javadoc:
No Javadoc available
Method code:
T removeLastD2(int d1);
No outgoing methods.
jfreerails.util.List2D.set
Javadoc:
No Javadoc available
Method code:
void set(int d1, int d2, T element);
No outgoing methods.
jfreerails.util.List2D.sizeD1
Javadoc:
No Javadoc available
Method code:
int sizeD1();
No outgoing methods.
jfreerails.util.List2D.sizeD2
Javadoc:
No Javadoc available
Method code:
int sizeD2(int d1);
No outgoing methods.
jfreerails.util.List2DDiff.addD1
Javadoc:
No Javadoc available
Method code:
public int addD1() {
return super.addDimension();
}
Outgoing Methods (calls):
jfreerails.util.List2DDiff.addD2
Javadoc:
No Javadoc available
Method code:
public int addD2(int d1, T element) {
return super.addElement(element, d1);
}
Outgoing Methods (calls):
jfreerails.util.List2DDiff.get
Javadoc:
No Javadoc available
Method code:
public T get(int d1, int d2) {
return super.get(d1, d2);
}
Outgoing Methods (calls):
jfreerails.util.List2DDiff.getUnderlyingList
Javadoc:
No Javadoc available
Method code:
@Override
Object getUnderlyingList() {
return underlyingList;
}
No outgoing methods.
jfreerails.util.List2DDiff.getUnderlyingSize
Javadoc:
No Javadoc available
Method code:
@Override
int getUnderlyingSize(int... dim) {
if(dim.length == 0)
return underlyingList.sizeD1();
if(dim.length == 1){
if (underlyingList.sizeD1() <= dim[0])
return -1;
return underlyingList.sizeD2(dim[0]);
}
throw new IllegalArgumentException(String.valueOf(dim.length));
}
Outgoing Methods (calls):
jfreerails.util.List2DDiff.removeLastD1
Javadoc:
No Javadoc available
Method code:
public int removeLastD1() {
return super.removeLastList();
}
Outgoing Methods (calls):
jfreerails.util.List2DDiff.removeLastD2
Javadoc:
No Javadoc available
Method code:
public T removeLastD2(int d1) {
return super.removeLast(d1);
}
Outgoing Methods (calls):
jfreerails.util.List2DDiff.set
Javadoc:
No Javadoc available
Method code:
public void set(int d1, int d2, T element) {
super.set(element, d1, d2);
}
Outgoing Methods (calls):
jfreerails.util.List2DDiff.sizeD1
Javadoc:
No Javadoc available
Method code:
public int sizeD1() {
return super.size();
}
Outgoing Methods (calls):
jfreerails.util.List2DDiff.sizeD2
Javadoc:
/** * Returns the size of the specified dimension in the 2D list. * * @param d1 the dimension index (0 for the first dimension, 1 for the second) * @return the size of the specified dimension */
Method code:
public int sizeD2(int d1) {
return super.size(d1);
}
Outgoing Methods (calls):
jfreerails.util.List2DDiff.uGet
Javadoc:
No Javadoc available
Method code:
@Override
T uGet(int... i) {
if (i.length != 2)
throw new IllegalArgumentException(String.valueOf(i.length));
return underlyingList.get(i[0], i[1]);
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
underlying = new List2DImpl<Object>(0);
map = new TreeMap<ListKey, Object>();
diffs = new List2DDiff<Object>(map, underlying, listid.test);
}
No outgoing methods.
jfreerails.util.List2DDiffTest.testAddD1
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List2DDiff.addD1()'
*/
public void testAddD1() {
underlying.addD1();
assertEquals(1, diffs.sizeD1());
assertEquals(1, diffs.getUnderlyingSize());
assertEquals(1, diffs.size());
diffs.addD1();
ListKey sizeKey = new ListKey(EndPoint, listid.test);
assertEquals(2, map.size());
assertTrue(map.containsKey(sizeKey));
assertEquals(new Integer(2), map.get(sizeKey));
assertEquals(2, diffs.sizeD1());
diffs.addD1();
assertEquals(3, diffs.sizeD1());
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.testAddD2
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List2DDiff.addD2(int, T)'
*/
public void testAddD2() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
assertEquals(2, diffs.sizeD2(0));
int i = diffs.addD2(0, String.valueOf(3));
assertEquals(2, i);
assertEquals(3, diffs.sizeD2(0));
i = diffs.addD2(0, String.valueOf(4));
assertEquals(3, i);
assertEquals(4, diffs.sizeD2(0));
assertEquals(String.valueOf(3), diffs.get(0, 2));
assertEquals(String.valueOf(4), diffs.get(0, 3));
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.testAddIntArray
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.ListXDDiffs.add(int...)'
*/
public void testAddIntArray() {
assertEquals(0, diffs.sizeD1());
diffs.addDimension();
ListKey sizeKey = new ListKey(EndPoint, listid.test);
assertEquals("There should be two values: EndPoint = 0 and EndPoint[0] = 0", 2, map.size());
assertTrue(map.containsKey(sizeKey));
assertEquals(new Integer(1), map.get(sizeKey));
assertEquals(1, diffs.sizeD1());
assertEquals(0, diffs.sizeD2(0));
diffs.addDimension(0);
assertEquals(1, diffs.sizeD2(0));
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.testAddingElementAlreadyPresent
Javadoc:
No Javadoc available
Method code:
public void testAddingElementAlreadyPresent(){
underlying.addD1();
underlying.addD2(0, new Integer(1));
diffs.removeLastD2(0);
diffs.addD2(0, new Integer(1));
assertEquals(0, map.size());
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.testAddingNullElement
Javadoc:
No Javadoc available
Method code:
public void testAddingNullElement(){
underlying.addD1();
underlying.addD2(0, null);
diffs.removeLastD2(0);
diffs.addD2(0, new Integer(1));
assertEquals(1, map.size());
diffs.removeLastD2(0);
diffs.addD2(0, null);
assertEquals(0, map.size());
diffs.addD2(0, null);
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.testBoundsOnGet
Javadoc:
No Javadoc available
Method code:
public void testBoundsOnGet(){
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
underlying.addD2(0, String.valueOf(3));
diffs.removeLastD2(0);
diffs.removeLastD2(0);
try {
assertEquals(1, diffs.size(0));
diffs.get(0, 2);
fail();
} catch (Exception e) {
}
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.testBoundsOnSet1
Javadoc:
No Javadoc available
Method code:
public void testBoundsOnSet1() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
try {
assertEquals(2, diffs.size(0));
diffs.set(0, 2, String.valueOf(3));
fail();
} catch (Exception e) {
}
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.testBoundsOnSet2
Javadoc:
No Javadoc available
Method code:
public void testBoundsOnSet2() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
underlying.addD2(0, String.valueOf(3));
diffs.removeLastD2(0);
diffs.removeLastD2(0);
try {
assertEquals(1, diffs.size(0));
diffs.set(0, 2, String.valueOf(3));
fail();
} catch (Exception e) {
}
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.testGetIntInt
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List2DDiff.get(int, int)'
*/
public void testGetIntInt() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
assertEquals(String.valueOf(1), underlying.get(0, 0));
assertEquals(String.valueOf(1), diffs.get(0, 0));
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.testRemoveLastD1
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List2DDiff.removeLastD1()'
*/
public void testRemoveLastD1() {
underlying.addD1();
underlying.addD1();
assertEquals(2, diffs.sizeD1());
int i = diffs.removeLastD1();
assertEquals(1, i);
assertEquals(1, diffs.sizeD1());
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.testRemoveLastD2
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List2DDiff.removeLastD2(int)'
*/
public void testRemoveLastD2() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
Object removed = diffs.removeLastD2(0);
assertEquals(String.valueOf(2), removed);
assertEquals(2, underlying.sizeD2(0));
assertEquals(2, diffs.getUnderlyingSize(0));
assertEquals(1, map.size());
assertEquals(1, diffs.sizeD2(0));
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.testReverting2OriginalState1
Javadoc:
No Javadoc available
Method code:
public void testReverting2OriginalState1(){
underlying.addD1();
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
diffs.addD1();
assertEquals(3, diffs.sizeD1());
assertEquals(0, diffs.sizeD2(2));
diffs.removeLastD1();
assertEquals(2, diffs.sizeD1());
assertEquals(2, underlying.sizeD1());
assertEquals(0, map.size());
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.testReverting2OriginalState2
Javadoc:
No Javadoc available
Method code:
public void testReverting2OriginalState2(){
underlying.addD1();
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
diffs.addD1();
diffs.addD2(2, String.valueOf(3));
diffs.addD2(2, String.valueOf(33));
assertEquals(2, diffs.sizeD2(2));
assertEquals(String.valueOf(3), diffs.get(2, 0));
assertEquals(String.valueOf(33), diffs.get(2, 1));
Object removed = diffs.removeLastD2(2);
assertEquals(String.valueOf(33), removed);
removed = diffs.removeLastD2(2);
assertEquals(String.valueOf(3), removed);
assertEquals(0, diffs.sizeD2(2));
assertEquals(3, diffs.sizeD1());
assertEquals(0, diffs.sizeD2(2));
diffs.removeLastD1();
assertEquals(2, diffs.sizeD1());
assertEquals(2, underlying.sizeD1());
assertEquals(0, map.size());
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.testSetIntIntT
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List2DDiff.set(int, int, T)'
*/
public void testSetIntIntT() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
assertEquals(String.valueOf(2), diffs.get(0, 1));
diffs.set(0, 1, String.valueOf(22));
assertEquals(String.valueOf(22), diffs.get(0, 1));
diffs.addD2(0, String.valueOf(3));
assertEquals(String.valueOf(3), diffs.get(0, 2));
diffs.set(0, 2, String.valueOf(33));
assertEquals(String.valueOf(33), diffs.get(0, 2));
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.testSettingNullElement
Javadoc:
No Javadoc available
Method code:
public void testSettingNullElement(){
underlying.addD1();
underlying.addD2(0, null);
underlying.addD2(0, new Integer(1));
assertEquals(null, diffs.get(0,0));
diffs.set(0, 0, new Integer(0));
assertEquals(new Integer(0), diffs.get(0,0));
assertEquals(new Integer(1), diffs.get(0,1));
diffs.set(0, 1, null);
assertEquals(null, diffs.get(0,1));
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.testSizeD1
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List2DDiff.sizeD1()'
*/
public void testSizeD1() {
assertEquals(0, diffs.sizeD1());
underlying.addD1();
assertEquals(1, diffs.sizeD1());
}
Outgoing Methods (calls):
jfreerails.util.List2DDiffTest.testSizeD2
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List2DDiff.sizeD2(int)'
*/
public void testSizeD2() {
underlying.addD1();
assertEquals(1, diffs.sizeD1());
assertEquals(0, diffs.sizeD2(0));
underlying.addD2(0, String.valueOf(1));
assertEquals(1, diffs.sizeD2(0));
}
Outgoing Methods (calls):
jfreerails.util.List2DImpl.addD1
Javadoc:
No Javadoc available
Method code:
public int addD1() {
elementData.add(new ArrayList<T>());
return elementData.size() -1;
}
No outgoing methods.
jfreerails.util.List2DImpl.addD2
Javadoc:
No Javadoc available
Method code:
public int addD2(int d1, T element) {
ArrayList<T> d2 = elementData.get(d1);
int index = d2.size();
d2.add(element);
return index;
}
No outgoing methods.
jfreerails.util.List2DImpl.get
Javadoc:
No Javadoc available
Method code:
public T get(int d1, int d2) {
return elementData.get(d1).get(d2);
}
No outgoing methods.
jfreerails.util.List2DImpl.removeLastD1
Javadoc:
No Javadoc available
Method code:
public int removeLastD1() {
int last = elementData.size() -1;
if(sizeD2(last) != 0)
throw new IllegalStateException(String.valueOf(last));
elementData.remove(last);
return last;
}
Outgoing Methods (calls):
jfreerails.util.List2DImpl.removeLastD2
Javadoc:
No Javadoc available
Method code:
public T removeLastD2(int d1) {
int last = elementData.get(d1).size() -1;
T element = elementData.get(d1).get(last);
elementData.get(d1).remove(last);
return element;
}
No outgoing methods.
jfreerails.util.List2DImpl.set
Javadoc:
No Javadoc available
Method code:
public void set(int d1, int d2, T element) {
elementData.get(d1).set(d2, element);
}
No outgoing methods.
jfreerails.util.List2DImpl.sizeD1
Javadoc:
No Javadoc available
Method code:
public int sizeD1() {
return elementData.size();
}
No outgoing methods.
jfreerails.util.List2DImpl.sizeD2
Javadoc:
No Javadoc available
Method code:
public int sizeD2(int d1) {
return elementData.get(d1).size();
}
No outgoing methods.
jfreerails.util.List3D.addD1
Javadoc:
No Javadoc available
Method code:
int addD1();
No outgoing methods.
jfreerails.util.List3D.addD2
Javadoc:
No Javadoc available
Method code:
int addD2(int d1);
No outgoing methods.
jfreerails.util.List3D.addD3
Javadoc:
No Javadoc available
Method code:
int addD3(int d1, int d2, T element);
No outgoing methods.
jfreerails.util.List3D.get
Javadoc:
No Javadoc available
Method code:
T get(int d1, int d2, int d3);
No outgoing methods.
jfreerails.util.List3D.removeLastD1
Javadoc:
No Javadoc available
Method code:
void removeLastD1();
No outgoing methods.
jfreerails.util.List3D.removeLastD2
Javadoc:
No Javadoc available
Method code:
void removeLastD2(int d1);
No outgoing methods.
jfreerails.util.List3D.removeLastD3
Javadoc:
No Javadoc available
Method code:
T removeLastD3(int d1, int d2);
No outgoing methods.
jfreerails.util.List3D.set
Javadoc:
No Javadoc available
Method code:
void set(int d1, int d2, int d3, T element);
No outgoing methods.
jfreerails.util.List3D.sizeD1
Javadoc:
No Javadoc available
Method code:
int sizeD1();
No outgoing methods.
jfreerails.util.List3D.sizeD2
Javadoc:
No Javadoc available
Method code:
int sizeD2(int d1);
No outgoing methods.
jfreerails.util.List3D.sizeD3
Javadoc:
No Javadoc available
Method code:
int sizeD3(int d1, int d2);
No outgoing methods.
jfreerails.util.List3DDiff.addD1
Javadoc:
No Javadoc available
Method code:
public int addD1() {
return super.addDimension();
}
Outgoing Methods (calls):
jfreerails.util.List3DDiff.addD2
Javadoc:
No Javadoc available
Method code:
public int addD2(int d1) {
return super.addDimension(d1);
}
Outgoing Methods (calls):
jfreerails.util.List3DDiff.addD3
Javadoc:
No Javadoc available
Method code:
public int addD3(int d1, int d2, T element) {
return super.addElement(element, d1, d2);
}
Outgoing Methods (calls):
jfreerails.util.List3DDiff.get
Javadoc:
No Javadoc available
Method code:
public List<T> get(int d1, int d2) {
List<T> list = new ArrayList<T>();
for(int d3 = 0; d3 < sizeD3(d1, d2); d3++) {
list.add(get(d1, d2, d3));
}
return list;
}
Outgoing Methods (calls):
jfreerails.util.List3DDiff.getUnderlyingList
Javadoc:
No Javadoc available
Method code:
@Override
Object getUnderlyingList() {
return underlyingList;
}
No outgoing methods.
jfreerails.util.List3DDiff.getUnderlyingSize
Javadoc:
No Javadoc available
Method code:
@Override
int getUnderlyingSize(int... dim) {
if(dim.length == 0)
return underlyingList.sizeD1();
if(dim.length == 1){
if (underlyingList.sizeD1() <= dim[0])
return -1;
return underlyingList.sizeD2(dim[0]);
}
if(dim.length == 2){
if (underlyingList.sizeD1() <= dim[0])
return -1;
if (underlyingList.sizeD2(dim[0]) <= dim[1])
return -1;
return underlyingList.sizeD3(dim[0], dim[1]);
}
throw new IllegalArgumentException(String.valueOf(dim.length));
}
Outgoing Methods (calls):
jfreerails.util.List3DDiff.removeLastD1
Javadoc:
No Javadoc available
Method code:
public void removeLastD1() {
super.removeLastList();
}
Outgoing Methods (calls):
jfreerails.util.List3DDiff.removeLastD2
Javadoc:
No Javadoc available
Method code:
public void removeLastD2(int d1) {
super.removeLastList(d1);
}
Outgoing Methods (calls):
jfreerails.util.List3DDiff.removeLastD3
Javadoc:
No Javadoc available
Method code:
public T removeLastD3(int d1, int d2) {
return super.removeLast(d1, d2);
}
Outgoing Methods (calls):
jfreerails.util.List3DDiff.set
Javadoc:
No Javadoc available
Method code:
public void set(int d1, int d2, int d3, T element) {
super.set(element, d1, d2, d3);
}
Outgoing Methods (calls):
jfreerails.util.List3DDiff.sizeD1
Javadoc:
No Javadoc available
Method code:
public int sizeD1() {
return super.size();
}
Outgoing Methods (calls):
jfreerails.util.List3DDiff.sizeD2
Javadoc:
No Javadoc available
Method code:
public int sizeD2(int d1) {
return super.size(d1);
}
Outgoing Methods (calls):
jfreerails.util.List3DDiff.sizeD3
Javadoc:
No Javadoc available
Method code:
public int sizeD3(int d1, int d2) {
return super.size(d1, d2);
}
Outgoing Methods (calls):
jfreerails.util.List3DDiff.uGet
Javadoc:
No Javadoc available
Method code:
@Override
T uGet(int... i) {
if (i.length != 3)
throw new IllegalArgumentException();
return underlyingList.get(i[0], i[1], i[2]);
}
Outgoing Methods (calls):
jfreerails.util.List3DDiffTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
underlying = new List3DImpl<Object>(0, 0);
map = new TreeMap<ListKey, Object>();
diffs = new List3DDiff<Object>(map, underlying, listid.test);
}
No outgoing methods.
jfreerails.util.List3DDiffTest.testAddD1
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List3DDiff.addD1()'
*/
public void testAddD1() {
diffs.addD1();
assertEquals(1, diffs.sizeD1());
diffs.addD1();
assertEquals(2, diffs.sizeD1());
}
Outgoing Methods (calls):
jfreerails.util.List3DDiffTest.testAddD2
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List3DDiff.addD2(int)'
*/
public void testAddD2() {
underlying.addD1();
underlying.addD1();
diffs.addD2(0);
assertEquals(1, diffs.sizeD2(0));
diffs.addD2(0);
assertEquals(2, diffs.sizeD2(0));
diffs.addD2(1);
assertEquals(1, diffs.sizeD2(1));
}
Outgoing Methods (calls):
jfreerails.util.List3DDiffTest.testAddD3
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List3DDiff.addD3(int, int, T)'
*/
public void testAddD3() {
underlying.addD1();
underlying.addD1();
underlying.addD2(1);
underlying.addD2(1);
diffs.addD3(1, 0, new Integer(5));
assertEquals(1, diffs.sizeD3(1, 0));
diffs.addD3(1, 1, new Integer(5));
assertEquals(1, diffs.sizeD3(1, 1));
}
Outgoing Methods (calls):
jfreerails.util.List3DDiffTest.testGetIntIntInt
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List3DDiff.get(int, int, int)'
*/
public void testGetIntIntInt() {
underlying.addD1();
underlying.addD1();
underlying.addD2(1);
underlying.addD2(1);
underlying.addD3(1, 1, new Integer(1));
assertEquals(new Integer(1), diffs.get(1,1,0));
diffs.addD3(1, 1, new Integer(2));
diffs.addD3(1, 1, new Integer(3));
assertEquals(new Integer(2), diffs.get(1,1,1));
assertEquals(new Integer(3), diffs.get(1,1,2));
}
Outgoing Methods (calls):
jfreerails.util.List3DDiffTest.testGetUnderlyingSize
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List3DDiff.getUnderlyingSize(int...)'
*/
public void testGetUnderlyingSize() {
assertEquals(-1, diffs.getUnderlyingSize(0,0));
assertEquals(-1, diffs.getUnderlyingSize(0));
assertEquals(0, diffs.getUnderlyingSize());
assertEquals(-1, diffs.getUnderlyingSize(1, 0));
assertEquals(-1, diffs.getUnderlyingSize(0, 1));
underlying.addD1();
underlying.addD1();
assertEquals(2, diffs.getUnderlyingSize());
assertEquals(0, diffs.getUnderlyingSize(1));
assertEquals(0, diffs.getUnderlyingSize(0));
}
Outgoing Methods (calls):
jfreerails.util.List3DDiffTest.testRemoveLastD1
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List3DDiff.removeLastD1()'
*/
public void testRemoveLastD1() {
underlying.addD1();
underlying.addD1();
assertEquals(2, diffs.sizeD1());
diffs.removeLastD1();
assertEquals(1, diffs.sizeD1());
diffs.removeLastD1();
assertEquals(0, diffs.sizeD1());
try{
diffs.removeLastD1();
fail();
}catch (Exception e) {
}
}
Outgoing Methods (calls):
jfreerails.util.List3DDiffTest.testRemoveLastD2
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List3DDiff.removeLastD2(int)'
*/
public void testRemoveLastD2() {
underlying.addD1();
underlying.addD2(0);
underlying.addD2(0);
underlying.addD2(0);
assertEquals(3, diffs.sizeD2(0));
diffs.removeLastD2(0);
assertEquals(2, diffs.sizeD2(0));
diffs.removeLastD2(0);
diffs.removeLastD2(0);
assertEquals(0, diffs.sizeD2(0));
try{
diffs.removeLastD2(0);
fail();
}catch (Exception e) {
}
}
Outgoing Methods (calls):
jfreerails.util.List3DDiffTest.testRemoveLastD3
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List3DDiff.removeLastD3(int, int)'
*/
public void testRemoveLastD3() {
underlying.addD1();
underlying.addD2(0);
underlying.addD3(0,0, new Integer(1));
underlying.addD3(0,0, new Integer(2));
underlying.addD3(0,0, new Integer(3));
assertEquals(3, diffs.sizeD3(0,0));
diffs.removeLastD3(0, 0);
assertEquals(2, diffs.sizeD3(0,0));
diffs.removeLastD3(0, 0);
assertEquals(1, diffs.sizeD3(0,0));
diffs.removeLastD3(0, 0);
assertEquals(0, diffs.sizeD3(0,0));
try{
diffs.removeLastD3(0, 0);
fail();
}catch (Exception e) {
}
}
Outgoing Methods (calls):
jfreerails.util.List3DDiffTest.testSetIntIntIntT
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List3DDiff.set(int, int, int, T)'
*/
public void testSetIntIntIntT() {
underlying.addD1();
underlying.addD2(0);
underlying.addD3(0,0, new Integer(1));
assertEquals(new Integer(1), diffs.get(0, 0, 0));
diffs.addD3(0,0, new Integer(2));
assertEquals(new Integer(2), diffs.get(0, 0, 1));
diffs.set(0,0,0, new Integer(11));
assertEquals(new Integer(11), diffs.get(0, 0, 0));
diffs.set(0,0,1, new Integer(22));
assertEquals(new Integer(22), diffs.get(0, 0, 1));
}
Outgoing Methods (calls):
jfreerails.util.List3DDiffTest.testSizeDx
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List3DDiff.sizeD1()'
*/
public void testSizeDx() {
assertEquals(0, diffs.sizeD1());
underlying.addD1();
assertEquals(1, diffs.sizeD1());
assertEquals(0, diffs.sizeD2(0));
underlying.addD2(0);
assertEquals(1, diffs.sizeD2(0));
assertEquals(0, diffs.sizeD3(0,0));
underlying.addD3(0,0, new Integer(4));
underlying.addD3(0,0, new Integer(4));
assertEquals(2, diffs.sizeD3(0,0));
}
Outgoing Methods (calls):
jfreerails.util.List3DDiffTest.testUGet
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.util.List3DDiff.uGet(int...)'
*/
public void testUGet() {
underlying.addD1();
underlying.addD2(0);
underlying.addD3(0,0, new Integer(1));
assertEquals(new Integer(1), diffs.uGet(0,0,0));
}
Outgoing Methods (calls):
jfreerails.util.List3DImpl.addD1
Javadoc:
No Javadoc available
Method code:
public int addD1() {
ArrayList<ArrayList<T>> dim2 = new ArrayList<ArrayList<T>>();
elementData.add(dim2);
return elementData.size() -1;
}
No outgoing methods.
jfreerails.util.List3DImpl.addD2
Javadoc:
No Javadoc available
Method code:
public int addD2(int d1) {
ArrayList<ArrayList<T>> dim2 = elementData.get(d1);
dim2.add(new ArrayList<T>() );
return dim2.size()-1;
}
No outgoing methods.
jfreerails.util.List3DImpl.addD3
Javadoc:
No Javadoc available
Method code:
public int addD3(int d1, int d2, T element) {
ArrayList<T> dim3 = elementData.get(d1).get(d2);
dim3.add(element);
return dim3.size()-1;
}
No outgoing methods.
jfreerails.util.List3DImpl.get
Javadoc:
No Javadoc available
Method code:
public T get(int d1, int d2, int d3) {
return elementData.get(d1).get(d2).get(d3);
}
No outgoing methods.
jfreerails.util.List3DImpl.removeLastD1
Javadoc:
No Javadoc available
Method code:
public void removeLastD1() {
int last = elementData.size()-1;
if(elementData.get(last).size() > 0)
throw new IllegalStateException(String.valueOf(last));
elementData.remove(last);
}
No outgoing methods.
jfreerails.util.List3DImpl.removeLastD2
Javadoc:
No Javadoc available
Method code:
public void removeLastD2(int d1) {
ArrayList<ArrayList<T>> dim2 = elementData.get(d1);
int last = dim2.size()-1;
ArrayList<T> dim3 = dim2.get(last);
if(dim3.size() > 0)
throw new IllegalStateException(String.valueOf(d1));
dim2.remove(last);
}
No outgoing methods.
jfreerails.util.List3DImpl.removeLastD3
Javadoc:
No Javadoc available
Method code:
public T removeLastD3(int d1, int d2) {
ArrayList<T> dim3 = elementData.get(d1).get(d2);
int last = dim3.size()-1;
T element = dim3.get(last);
dim3.remove(last);
return element;
}
No outgoing methods.
jfreerails.util.List3DImpl.set
Javadoc:
No Javadoc available
Method code:
public void set(int d1, int d2, int d3, T element) {
ArrayList<T> dim3 = elementData.get(d1).get(d2);
dim3.set(d3, element);
}
No outgoing methods.
jfreerails.util.List3DImpl.sizeD1
Javadoc:
No Javadoc available
Method code:
public int sizeD1() {
return elementData.size();
}
No outgoing methods.
jfreerails.util.List3DImpl.sizeD2
Javadoc:
No Javadoc available
Method code:
public int sizeD2(int d1) {
return elementData.get(d1).size();
}
No outgoing methods.
jfreerails.util.List3DImpl.sizeD3
Javadoc:
No Javadoc available
Method code:
public int sizeD3(int d1, int d2) {
return elementData.get(d1).get(d2).size();
}
No outgoing methods.
jfreerails.util.ListKey.compareTo
Javadoc:
No Javadoc available
Method code:
public int compareTo(ListKey o) {
if(o.listID != listID)
return o.listID.ordinal() - listID.ordinal();
if(index.length != o.index.length)
return index.length -o.index.length;
for (int i = 0; i < index.length; i++) {
if(index[i] != o.index[i])
return index[i] -o.index[i];
}
if(o.type != type)
return o.type.ordinal() - type.ordinal();
return 0;
}
No outgoing methods.
jfreerails.util.ListKey.getIndex
Javadoc:
No Javadoc available
Method code:
public int[] getIndex() {
return index.clone();
}
Outgoing Methods (calls):
jfreerails.util.ListKey.getListID
Javadoc:
No Javadoc available
Method code:
public Enum getListID() {
return listID;
}
No outgoing methods.
jfreerails.util.ListKey.getType
Javadoc:
No Javadoc available
Method code:
public Type getType() {
return type;
}
No outgoing methods.
jfreerails.util.ListXDDiffs.add2Array
Javadoc:
No Javadoc available
Method code:
static int[] add2Array(int[] dim, int last) {
int[] array = new int[dim.length + 1];
for (int i = 0; i < dim.length; i++) {
array[i] = dim[i];
}
array[array.length - 1] = last;
return array;
}
No outgoing methods.
jfreerails.util.ListXDDiffs.addDimension
Javadoc:
No Javadoc available
Method code:
public int addDimension(int... dim) {
int i = size(dim);
ListKey sizeKeyA = new ListKey(ListKey.Type.EndPoint, listID, dim);
int[] subArray = add2Array(dim, i);
ListKey sizeKeyB = new ListKey(ListKey.Type.EndPoint, listID, subArray);
diffs.put(sizeKeyA, new Integer(i + 1));
diffs.put(sizeKeyB, new Integer(0));
return i;
}
Outgoing Methods (calls):
jfreerails.util.ListXDDiffs.addElement
Javadoc:
No Javadoc available
Method code:
public int addElement(T element, int... dim) {
int sizeBefore = size(dim);
int[] index = add2Array(dim, sizeBefore);
setElementDiff: {
if (getUnderlyingSize(dim) > sizeBefore) {
T uElement = uGet(index);
if (Utils.equal(uElement, element)) {
// We are reading an element that was removed, in which
// case we don't store a diff.
break setElementDiff;
}
}
ListKey elementKey = new ListKey(ListKey.Type.Element, listID,
index);
diffs.put(elementKey, element);
}
setSize(sizeBefore + 1, dim);
return sizeBefore;
}
Outgoing Methods (calls):
jfreerails.util.ListXDDiffs.checkBounds
Javadoc:
No Javadoc available
Method code:
private int[] checkBounds(int... i) {
int[] dim = removeFromArray(i);
int last = i[i.length - 1];
if (last >= size(dim))
throw new IndexOutOfBoundsException(String.valueOf(last));
return dim;
}
Outgoing Methods (calls):
jfreerails.util.ListXDDiffs.get
Javadoc:
No Javadoc available
Method code:
@SuppressWarnings("unchecked")
public T get(int... i) {
checkBounds(i);
ListKey elementKey = new ListKey(ListKey.Type.Element, listID, i);
if (diffs.containsKey(elementKey)) {
return (T) diffs.get(elementKey);
}
return uGet(i);
}
Outgoing Methods (calls):
jfreerails.util.ListXDDiffs.getUnderlyingList
Javadoc:
No Javadoc available
Method code:
abstract Object getUnderlyingList();
No outgoing methods.
jfreerails.util.ListXDDiffs.getUnderlyingSize
Javadoc:
/** * Returns the size of the underlying list at the specified dimension or -1 * if the underlying list does not have the specified dimension. */
Method code:
/**
* Returns the size of the underlying list at the specified dimension or -1
* if the underlying list does not have the specified dimension.
*/
abstract int getUnderlyingSize(int... dim);
No outgoing methods.
jfreerails.util.ListXDDiffs.removeFromArray
Javadoc:
No Javadoc available
Method code:
static int[] removeFromArray(int[] dim) {
int[] array = new int[dim.length - 1];
for (int i = 0; i < dim.length - 1; i++) {
array[i] = dim[i];
}
return array;
}
No outgoing methods.
jfreerails.util.ListXDDiffs.removeLast
Javadoc:
No Javadoc available
Method code:
@SuppressWarnings("unchecked")
public T removeLast(int... dim) {
T toRemove;
int last = size(dim) - 1;
int[] array = add2Array(dim, last);
ListKey elementKey = new ListKey(ListKey.Type.Element, listID, array);
if (diffs.containsKey(elementKey)) {
toRemove = (T) diffs.remove(elementKey);
} else {
toRemove = uGet(array);
}
setSize(last, dim);
return toRemove;
}
Outgoing Methods (calls):
jfreerails.util.ListXDDiffs.removeLastList
Javadoc:
No Javadoc available
Method code:
int removeLastList(int... dim) {
int last = size(dim) - 1;
// Check that the list we are removing is empty.
int[] array = add2Array(dim, last);
if (0 != size(array))
throw new IllegalStateException();
ListKey sizeKeyB = new ListKey(ListKey.Type.EndPoint, listID, array);
diffs.remove(sizeKeyB);
setSize(last, dim);
return last;
}
Outgoing Methods (calls):
jfreerails.util.ListXDDiffs.set
Javadoc:
No Javadoc available
Method code:
public void set(T element, int... i) {
// Check bounds..
checkBounds(i);
int last = i[i.length - 1];
int[] dim = checkBounds(i);
ListKey elementKey = new ListKey(ListKey.Type.Element, listID, i);
boolean b = getUnderlyingSize(dim) > last;
if (b && Utils.equal(uGet(i), element)) {
if (diffs.containsKey(elementKey))
diffs.remove(elementKey);
} else {
diffs.put(elementKey, element);
}
}
Outgoing Methods (calls):
jfreerails.util.ListXDDiffs.setSize
Javadoc:
/** * Updates the diffs map by either removing or adding a size entry based on the provided dimensions. * If the current underlying size matches the specified size, the corresponding entry is removed. * Otherwise, a new entry is added with the specified size. * * @param size The new size value to set for the specified dimensions. * @param dim Variable-length argument array representing the dimensions used to identify the size key. */
Method code:
private void setSize(int size, int... dim) {
ListKey sizeKey = new ListKey(ListKey.Type.EndPoint, listID, dim);
if (getUnderlyingSize(dim) == size) {
diffs.remove(sizeKey);
} else {
diffs.put(sizeKey, new Integer(size));
}
}
Outgoing Methods (calls):
jfreerails.util.ListXDDiffs.size
Javadoc:
No Javadoc available
Method code:
public int size(int... i) {
ListKey sizeKey = new ListKey(ListKey.Type.EndPoint, listID, i);
if (diffs.containsKey(sizeKey)) {
Integer size = (Integer) diffs.get(sizeKey);
return size.intValue();
}
return getUnderlyingSize(i);
}
Outgoing Methods (calls):
jfreerails.util.ListXDDiffs.uGet
Javadoc:
No Javadoc available
Method code:
abstract T uGet(int... i);
No outgoing methods.
jfreerails.util.ListXDDiffsTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
super.setUp();
map = new TreeMap<ListKey, Object>();
list1d = new List1DDiff<Object>(map, list1d, listid.list1);
list2d = new List2DDiff<Object>(map, list2d, listid.list2);
list3d = new List3DDiff<Object>(map, list3d, listid.list3);
}
Outgoing Methods (calls):
jfreerails.util.ListXDTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
list1d = new List1DImpl<Object>();
list2d = new List2DImpl<Object>(5);
list3d = new List3DImpl<Object>(3, 2);
}
No outgoing methods.
jfreerails.util.ListXDTest.test3DList
Javadoc:
No Javadoc available
Method code:
public void test3DList(){
list3d = new List3DImpl<Object>(0, 0);
//Add a player
int playerId = list3d.addD1();
list3d.addD2(playerId);
list3d.addD2(playerId);
list3d.addD2(playerId);
//Then remove them
while(list3d.sizeD2(playerId)>0){
list3d.removeLastD2(playerId);
}
}
Outgoing Methods (calls):
jfreerails.util.ListXDTest.testAdd
Javadoc:
No Javadoc available
Method code:
public void testAdd(){
//Test initial size.
assertEquals(0, list1d.size());
assertEquals(5, list2d.sizeD1());
assertEquals(0, list2d.sizeD2(0));
//Add an object
Integer i = new Integer(4);
assertEquals(0, list1d.add(i));
assertEquals(0, list2d.addD2(2, i));
assertEquals(1, list1d.size());
assertEquals(5, list2d.sizeD1());
assertEquals(1, list2d.sizeD2(2));
assertEquals(0, list2d.sizeD2(0));
}
Outgoing Methods (calls):
jfreerails.util.ListXDTest.testHashCodeAndEquals
Javadoc:
No Javadoc available
Method code:
public void testHashCodeAndEquals(){
Integer i = new Integer(5);
Integer ii = new Integer(53);
//1d
list1d.add(i);
Object copy = Utils.cloneBySerialisation(list1d);
assertEquals(copy, list1d);
assertEquals(copy.hashCode(), list1d.hashCode());
list1d.add(ii);
assertFalse(copy.equals(list1d));
//2d
list2d.addD2(0, i);
copy = Utils.cloneBySerialisation(list2d);
assertEquals(copy, list2d);
assertEquals(copy.hashCode(), list2d.hashCode());
list2d.addD2(0, ii);
assertFalse(copy.equals(list2d));
//3d
list3d.addD3(0, 1, i);
copy = Utils.cloneBySerialisation(list3d);
assertEquals(copy, list3d);
assertEquals(copy.hashCode(), list3d.hashCode());
list3d.addD3(0, 1, ii);
assertFalse(copy.equals(list3d));
}
Outgoing Methods (calls):
jfreerails.util.ListXDTest.testRemove
Javadoc:
No Javadoc available
Method code:
public void testRemove(){
Integer i = new Integer(4);
list2d.addD2(4, i);
try{
list2d.removeLastD1();
fail();
}catch (Exception e) {
//An exception should be thrown since the list we are trying to remove is not empty.
}
list3d.addD3(2,1,i);
//We now should be able to remove the last
try{
list3d.removeLastD1();
fail();
}catch (Exception e) {
//An exception should be thrown since the list we are trying to remove is not empty.
}
try{
list3d.removeLastD2(3);
fail();
}catch (Exception e) {
//An exception should be thrown since the list we are trying to remove is not empty.
}
}
Outgoing Methods (calls):
jfreerails.util.Pair.getA
Javadoc:
No Javadoc available
Method code:
public A getA() {
return e1;
}
No outgoing methods.
jfreerails.util.Pair.getB
Javadoc:
No Javadoc available
Method code:
public B getB() {
return e2;
}
No outgoing methods.
jfreerails.util.Unknown.finished
Javadoc:
No Javadoc available
Method code:
public void finished() {
}
No outgoing methods.
jfreerails.util.Unknown.nextStep
Javadoc:
No Javadoc available
Method code:
public void nextStep(int max) {
}
No outgoing methods.
jfreerails.util.Unknown.setValue
Javadoc:
No Javadoc available
Method code:
public void setValue(int i) {
}
No outgoing methods.
jfreerails.util.Utils.capitalizeEveryWord
Javadoc:
No Javadoc available
Method code:
public static String capitalizeEveryWord(String str) {
StringBuffer result = new StringBuffer();
StringTokenizer tok = new StringTokenizer(str);
while (tok.hasMoreTokens()) {
String token = tok.nextToken().toLowerCase();
result.append(Character.toUpperCase(token.charAt(0))
+ token.substring(1) + " ");
}
return result.toString().trim();
}
No outgoing methods.
jfreerails.util.Utils.cloneBySerialisation
Javadoc:
No Javadoc available
Method code:
public static Serializable cloneBySerialisation(Serializable m) {
try {
byte[] bytes = write2ByteArray(m);
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ObjectInputStream objectIn = new ObjectInputStream(in);
Serializable o;
o = (Serializable) objectIn.readObject();
return o;
} catch (ClassNotFoundException e) {
// Should never happen.
throw new IllegalStateException();
} catch (IOException e) {
// Should never happen.
e.printStackTrace();
throw new IllegalStateException();
}
}
Outgoing Methods (calls):
jfreerails.util.Utils.equal
Javadoc:
/** * Returns true if the objects are equal or both null, otherwise returns * false. Does not throw null pointer exceptions when either of the objects * is null. */
Method code:
/**
* Returns true if the objects are equal or both null, otherwise returns
* false. Does not throw null pointer exceptions when either of the objects
* is null.
*/
public static boolean equal(Object a, Object b) {
if (null == a || null == b) {
return null == a && null == b;
}
return a.equals(b);
}
No outgoing methods.
jfreerails.util.Utils.equalsBySerialization
Javadoc:
No Javadoc available
Method code:
public static boolean equalsBySerialization(Serializable a, Serializable b) {
byte[] bytesA = write2ByteArray(a);
byte[] bytesB = write2ByteArray(b);
if (bytesA.length != bytesB.length)
return false;
for (int i = 0; i < bytesA.length; i++) {
if (bytesA[i] != bytesB[i])
return false;
}
return true;
}
Outgoing Methods (calls):
jfreerails.util.Utils.findConstantFieldName
Javadoc:
No Javadoc available
Method code:
public static String findConstantFieldName(Object o) {
Field[] fields = o.getClass().getFields();
for (int i = 0; i < fields.length; i++) {
int modifiers = fields[i].getModifiers();
try {
if (Modifier.isStatic(modifiers)
&& Modifier.isPublic(modifiers)) {
Object o2 = fields[i].get(null);
if (o2.equals(o)) {
return fields[i].getName();
}
}
} catch (IllegalAccessException e) {
throw new IllegalStateException();
}
}
return null;
}
No outgoing methods.
jfreerails.util.Utils.hypotenuse
Javadoc:
No Javadoc available
Method code:
public static int hypotenuse(int a, int b) {
double d = Math.hypot(a, b);
return (int) Math.round(d);
}
No outgoing methods.
jfreerails.util.Utils.solveQuadratic
Javadoc:
/** * Returns the largest solution of the quadratic equation ax<sup><font * size="-1">2</font></sup> + bx + c = 0. * * @throws IllegalArgumentException * if <code>a == 0</code> * @throws IllegalArgumentException * if <code>(b * b - 4 * a * c) < 0</code> */
Method code:
/**
* Returns the largest solution of the quadratic equation ax<sup><font
* size="-1">2</font></sup> + bx + c = 0.
*
* @throws IllegalArgumentException
* if <code>a == 0</code>
* @throws IllegalArgumentException
* if <code>(b * b - 4 * a * c) < 0</code>
*/
public static double solveQuadratic(double a, double b, double c)
throws IllegalArgumentException {
if (a == 0) {
throw new IllegalArgumentException("a == 0");
}
double disc = b * b - 4 * a * c;
if (disc < 0)
throw new IllegalArgumentException("(b * b - 4 * a * c) < 0");
return (-b + StrictMath.sqrt(disc)) / (2 * a);
}
No outgoing methods.
jfreerails.util.Utils.write
Javadoc:
/** Used when debugging. */
Method code:
/** Used when debugging. */
public static void write(Serializable m, String fileName) {
try {
File f = new File(fileName);
OutputStream out = new FileOutputStream(f);
ObjectOutputStream objectOut = new ObjectOutputStream(out);
objectOut.writeObject(m);
objectOut.flush();
objectOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
No outgoing methods.
jfreerails.util.Utils.write2ByteArray
Javadoc:
No Javadoc available
Method code:
private static byte[] write2ByteArray(Serializable m) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ObjectOutputStream objectOut = new ObjectOutputStream(out);
objectOut.writeObject(m);
objectOut.flush();
} catch (IOException e) {
// Should never happen.
e.printStackTrace();
throw new IllegalStateException();
}
byte[] bytes = out.toByteArray();
return bytes;
}
No outgoing methods.
jfreerails.util.UtilsTest.testEqualsBySerialization
Javadoc:
No Javadoc available
Method code:
public void testEqualsBySerialization() {
Serializable a = new Point(10, 10);
Serializable b = new Point(10, 10);
Serializable c = new Point(30, 10);
assertTrue(Utils.equalsBySerialization(a, b));
assertTrue(Utils.equalsBySerialization(a, a));
assertTrue(Utils.equalsBySerialization(b, b));
assertTrue(Utils.equalsBySerialization(c, c));
assertFalse(Utils.equalsBySerialization(a, c));
}
Outgoing Methods (calls):
jfreerails.world.accounts.AddItemTransaction.deltaAssets
Javadoc:
No Javadoc available
Method code:
public Money deltaAssets() {
return amount.changeSign();
}
Outgoing Methods (calls):
jfreerails.world.accounts.AddItemTransaction.deltaCash
Javadoc:
No Javadoc available
Method code:
public Money deltaCash() {
return amount;
}
No outgoing methods.
jfreerails.world.accounts.AddItemTransaction.getCategory
Javadoc:
No Javadoc available
Method code:
public Category getCategory() {
return category;
}
No outgoing methods.
jfreerails.world.accounts.AddItemTransaction.getQuantity
Javadoc:
No Javadoc available
Method code:
public int getQuantity() {
return quantity;
}
No outgoing methods.
jfreerails.world.accounts.AddItemTransaction.getType
Javadoc:
No Javadoc available
Method code:
public int getType() {
return type;
}
No outgoing methods.
jfreerails.world.accounts.Bill.deltaAssets
Javadoc:
No Javadoc available
Method code:
public Money deltaAssets() {
return amount.changeSign();
}
Outgoing Methods (calls):
jfreerails.world.accounts.Bill.deltaCash
Javadoc:
/** * Returns the amount of money represented by this bill as a Money object. * This value represents the delta (change) in cash associated with the bill. * * @return the amount of money as a Money object */
Method code:
public Money deltaCash() {
return amount;
}
No outgoing methods.
jfreerails.world.accounts.Bill.getCategory
Javadoc:
No Javadoc available
Method code:
public Category getCategory() {
return category;
}
No outgoing methods.
jfreerails.world.accounts.BondTransaction.issueBond
Javadoc:
No Javadoc available
Method code:
public static BondTransaction issueBond(int interestRate) {
return new BondTransaction(Category.BOND, interestRate, 1,
BOND_VALUE_ISSUE);
}
No outgoing methods.
jfreerails.world.accounts.BondTransaction.repayBond
Javadoc:
No Javadoc available
Method code:
public static BondTransaction repayBond(int interestRate) {
return new BondTransaction(Category.BOND, interestRate, -1,
BOND_VALUE_REPAY);
}
No outgoing methods.
jfreerails.world.accounts.DeliverCargoReceipt.getCb
Javadoc:
No Javadoc available
Method code:
public CargoBatch getCb() {
return cb;
}
No outgoing methods.
jfreerails.world.accounts.DeliverCargoReceipt.getQuantity
Javadoc:
No Javadoc available
Method code:
public int getQuantity() {
return quantity;
}
No outgoing methods.
jfreerails.world.accounts.DeliverCargoReceipt.getStationId
Javadoc:
No Javadoc available
Method code:
public int getStationId() {
return stationId;
}
No outgoing methods.
jfreerails.world.accounts.DeliverCargoReceipt.getTrainId
Javadoc:
/** * Returns the ID of the train associated with this cargo receipt. * * @return the train ID as an integer. */
Method code:
public int getTrainId() {
return trainId;
}
No outgoing methods.
jfreerails.world.accounts.EconomicClimate.getBaseInterestRate
Javadoc:
No Javadoc available
Method code:
public int getBaseInterestRate() {
return baseInterestRate;
}
No outgoing methods.
jfreerails.world.accounts.Receipt.deltaAssets
Javadoc:
No Javadoc available
Method code:
public Money deltaAssets() {
return amount.changeSign();
}
Outgoing Methods (calls):
jfreerails.world.accounts.Receipt.deltaCash
Javadoc:
No Javadoc available
Method code:
public Money deltaCash() {
return amount;
}
No outgoing methods.
jfreerails.world.accounts.Receipt.getCategory
Javadoc:
No Javadoc available
Method code:
public Category getCategory() {
return category;
}
No outgoing methods.
jfreerails.world.accounts.StockTransaction.buyOrSellStock
Javadoc:
No Javadoc available
Method code:
public static StockTransaction buyOrSellStock(int playerId, int quantity,
Money stockPrice) {
// Buys another Players Stock, Uses another Category
Money value = new Money(stockPrice.getAmount() * quantity * -1);
return new StockTransaction(Transaction.Category.TRANSFER_STOCK,
playerId, quantity, value);
}
Outgoing Methods (calls):
jfreerails.world.accounts.StockTransaction.issueStock
Javadoc:
No Javadoc available
Method code:
public static StockTransaction issueStock(int playerId, int quantity,
Money pricePerShare) {
// Issue Stock of the Player
long temp = (pricePerShare.getAmount() * quantity);
temp = temp - temp - temp;
Money amount = new Money(temp).changeSign();
return new StockTransaction(Transaction.Category.ISSUE_STOCK, playerId,
quantity, amount);
}
Outgoing Methods (calls):
jfreerails.world.accounts.Transaction.deltaAssets
Javadoc:
No Javadoc available
Method code:
Money deltaAssets();
No outgoing methods.
jfreerails.world.accounts.Transaction.deltaCash
Javadoc:
/** Positive means credit. */
Method code:
/** Positive means credit. */
Money deltaCash();
No outgoing methods.
jfreerails.world.accounts.Transaction.getCategory
Javadoc:
No Javadoc available
Method code:
Category getCategory();
No outgoing methods.
jfreerails.world.accounts.TransactionAndTimeStamp.getT
Javadoc:
No Javadoc available
Method code:
public Transaction getT() {
return t;
}
No outgoing methods.
jfreerails.world.accounts.TransactionAndTimeStamp.getTimeStamp
Javadoc:
No Javadoc available
Method code:
public GameTime getTimeStamp() {
return timeStamp;
}
No outgoing methods.
jfreerails.world.cargo.CargoBatch.compareTo
Javadoc:
No Javadoc available
Method code:
public int compareTo(CargoBatch o) {
if (timeCreated != o.timeCreated)
return (int) (timeCreated - o.timeCreated);
if (cargoType != o.cargoType)
return (cargoType - o.cargoType);
if (stationOfOrigin != o.stationOfOrigin)
return (stationOfOrigin - o.stationOfOrigin);
if (sourceX != o.sourceX)
return (sourceX - o.sourceX);
if (sourceY != o.sourceY)
return (sourceY - o.sourceY);
return 0;
}
No outgoing methods.
jfreerails.world.cargo.CargoBatch.getCargoType
Javadoc:
No Javadoc available
Method code:
public int getCargoType() {
return cargoType;
}
No outgoing methods.
jfreerails.world.cargo.CargoBatch.getSourceX
Javadoc:
No Javadoc available
Method code:
public int getSourceX() {
return sourceX;
}
No outgoing methods.
jfreerails.world.cargo.CargoBatch.getSourceY
Javadoc:
No Javadoc available
Method code:
public int getSourceY() {
return sourceY;
}
No outgoing methods.
jfreerails.world.cargo.CargoBatch.getStationOfOrigin
Javadoc:
No Javadoc available
Method code:
public int getStationOfOrigin() {
return stationOfOrigin;
}
No outgoing methods.
jfreerails.world.cargo.CargoBatch.getTimeCreated
Javadoc:
No Javadoc available
Method code:
public long getTimeCreated() {
return timeCreated;
}
No outgoing methods.
jfreerails.world.cargo.CargoBundle.cargoBatchIterator
Javadoc:
/** * Note, calling hasNext() or next() on the returned iterator throws a * ConcurrentModificationException if this CargoBundle has changed since the * iterator was acquired. */
Method code:
/**
* Note, calling hasNext() or next() on the returned iterator throws a
* ConcurrentModificationException if this CargoBundle has changed since the
* iterator was acquired.
*/
Iterator<CargoBatch> cargoBatchIterator();
No outgoing methods.
jfreerails.world.cargo.CargoBundle.contains
Javadoc:
No Javadoc available
Method code:
boolean contains(CargoBatch cb);
No outgoing methods.
jfreerails.world.cargo.CargoBundle.getAmount
Javadoc:
No Javadoc available
Method code:
int getAmount(CargoBatch cb);
No outgoing methods.
jfreerails.world.cargo.CargoBundle.size
Javadoc:
No Javadoc available
Method code:
int size();
No outgoing methods.
jfreerails.world.cargo.CargoBundleTest.assertBundlesEqual
Javadoc:
No Javadoc available
Method code:
private void assertBundlesEqual(MutableCargoBundle a, MutableCargoBundle b) {
assertEquals(a, b);
assertEquals(a, a);
assertEquals(b, a);
ImmutableCargoBundle immA = a.toImmutableCargoBundle();
assertEquals(immA, immA);
assertEquals(immA, b);
ImmutableCargoBundle immB = b.toImmutableCargoBundle();
assertEquals(immA, immB);
Serializable cloneA = Utils.cloneBySerialisation(immA);
Serializable cloneB = Utils.cloneBySerialisation(immB);
assertEquals(cloneA, cloneB);
assertEquals(a, immB);
}
Outgoing Methods (calls):
jfreerails.world.cargo.CargoBundleTest.assertBundlesNotEqual
Javadoc:
No Javadoc available
Method code:
private void assertBundlesNotEqual(MutableCargoBundle a,
MutableCargoBundle b) {
assertFalse(a.equals(b));
assertFalse(b.equals(a));
assertFalse(a.toImmutableCargoBundle().equals(b));
assertFalse(a.toImmutableCargoBundle().equals(
b.toImmutableCargoBundle()));
assertFalse(a.equals(b.toImmutableCargoBundle()));
}
Outgoing Methods (calls):
jfreerails.world.cargo.CargoBundleTest.testEquals
Javadoc:
No Javadoc available
Method code:
public void testEquals() {
MutableCargoBundle bundle1 = new MutableCargoBundle();
MutableCargoBundle bundle2 = new MutableCargoBundle();
CargoBatch batch1 = new CargoBatch(1, 2, 3, 4, 5);
CargoBatch batch2 = new CargoBatch(4, 2, 3, 4, 5);
int q1 = 10;
int q2 = 20;
bundle1.addCargo(batch1, q1);
bundle1.addCargo(batch2, q2);
assertBundlesNotEqual(bundle1, bundle2);
bundle2.addCargo(batch2, q2);
assertBundlesNotEqual(bundle1, bundle2);
bundle2.addCargo(batch1, q1);
assertBundlesEqual(bundle1, bundle2);
}
Outgoing Methods (calls):
jfreerails.world.cargo.CargoType.getCategory
Javadoc:
No Javadoc available
Method code:
public Categories getCategory() {
return category;
}
No outgoing methods.
jfreerails.world.cargo.CargoType.getDisplayName
Javadoc:
/** Returns the name, replacing any underscores with spaces. */
Method code:
/** Returns the name, replacing any underscores with spaces. */
public String getDisplayName() {
return this.name.replace('_', ' ');
}
No outgoing methods.
jfreerails.world.cargo.CargoType.getName
Javadoc:
No Javadoc available
Method code:
public String getName() {
return name;
}
No outgoing methods.
jfreerails.world.cargo.CargoType.getNumberOfCategories
Javadoc:
No Javadoc available
Method code:
public static int getNumberOfCategories() {
return Categories.values().length;
}
Outgoing Methods (calls):
jfreerails.world.cargo.CargoType.getUnitWeight
Javadoc:
No Javadoc available
Method code:
public int getUnitWeight() {
return unitWeight;
}
No outgoing methods.
jfreerails.world.cargo.CargoTypeTest.testCargoType
Javadoc:
No Javadoc available
Method code:
public void testCargoType() {
// Test that invalid categories get rejected.
try {
new CargoType(10, "Test", Categories
.getCategory("Non valid category"));
fail();
} catch (Exception e) {
}
try {
new CargoType(10, "Test", Categories.Mail);
} catch (Exception e) {
fail();
}
}
Outgoing Methods (calls):
jfreerails.world.cargo.Categories.getCategory
Javadoc:
No Javadoc available
Method code:
public static Categories getCategory(String cat) {
for (Categories cmp : values()) {
if (cmp.toString().equals(cat)) {
return cmp;
}
}
throw new IllegalArgumentException("Category:" + cat + " unknown.");
}
Outgoing Methods (calls):
jfreerails.world.cargo.Categories.getNumber
Javadoc:
No Javadoc available
Method code:
public int getNumber() {
return nr;
}
No outgoing methods.
jfreerails.world.cargo.ImmutableCargoBundle.cargoBatchIterator
Javadoc:
No Javadoc available
Method code:
public Iterator<CargoBatch> cargoBatchIterator() {
return new Iterator<CargoBatch>() {
int index = 0;
public boolean hasNext() {
return index < batches.size();
}
public CargoBatch next() {
CargoBatch o = batches.get(index);
index++;
return o;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
Outgoing Methods (calls):
jfreerails.world.cargo.ImmutableCargoBundle.contains
Javadoc:
No Javadoc available
Method code:
public boolean contains(CargoBatch cb) {
for (int i = 0; i < batches.size(); i++) {
if (batches.get(i).equals(cb)) {
return true;
}
}
return false;
}
Outgoing Methods (calls):
jfreerails.world.cargo.ImmutableCargoBundle.getAmount
Javadoc:
No Javadoc available
Method code:
public int getAmount(CargoBatch cb) {
int amount = 0;
for (int i = 0; i < batches.size(); i++) {
if (batches.get(i).equals(cb)) {
amount += amounts.get(i);
}
}
return amount;
}
Outgoing Methods (calls):
jfreerails.world.cargo.ImmutableCargoBundle.size
Javadoc:
No Javadoc available
Method code:
public int size() {
return batches.size();
}
Outgoing Methods (calls):
jfreerails.world.cargo.MutableCargoBundle.addCargo
Javadoc:
No Javadoc available
Method code:
public void addCargo(CargoBatch cb, int amount) {
int amountAlready = this.getAmount(cb);
this.setAmount(cb, amount + amountAlready);
updateID++;
}
Outgoing Methods (calls):
jfreerails.world.cargo.MutableCargoBundle.cargoBatchIterator
Javadoc:
/** * Note, calling hasNext() or next() on the returned iterator throws a * ConcurrentModificationException if this CargoBundle has changed since the * iterator was acquired. */
Method code:
/**
* Note, calling hasNext() or next() on the returned iterator throws a
* ConcurrentModificationException if this CargoBundle has changed since the
* iterator was acquired.
*/
public Iterator<CargoBatch> cargoBatchIterator() {
final Iterator<CargoBatch> it = sortedMap.keySet().iterator();
/*
* A ConcurrentModificationException used to get thrown when the amount
* of cargo was set to 0, since this resulted in the key being removed
* from the hashmap. The iterator below throws a
* ConcurrentModificationException whenever this CargoBundle has been
* changed since the iterator was acquired. This should mean that if the
* cargo bundle gets changed while the iterator is in use, you will know
* about it straight away.
*/
return new Iterator<CargoBatch>() {
final int updateIDAtCreation = updateID;
public boolean hasNext() {
if (updateIDAtCreation != updateID) {
throw new ConcurrentModificationException();
}
return it.hasNext();
}
public CargoBatch next() {
if (updateIDAtCreation != updateID) {
throw new ConcurrentModificationException();
}
return it.next();
}
public void remove() {
throw new UnsupportedOperationException(
"Use CargoBundle.setAmount(CargoBatch cb, 0)");
}
};
}
No outgoing methods.
jfreerails.world.cargo.MutableCargoBundle.contains
Javadoc:
No Javadoc available
Method code:
public boolean contains(CargoBatch cb) {
return sortedMap.containsKey(cb);
}
No outgoing methods.
jfreerails.world.cargo.MutableCargoBundle.getAmount
Javadoc:
No Javadoc available
Method code:
public int getAmount(int cargoType) {
Iterator<CargoBatch> it = cargoBatchIterator();
int amount = 0;
while (it.hasNext()) {
CargoBatch cb = it.next();
if (cb.getCargoType() == cargoType) {
amount += getAmount(cb);
}
}
return amount;
}
Outgoing Methods (calls):
jfreerails.world.cargo.MutableCargoBundle.setAmount
Javadoc:
No Javadoc available
Method code:
public void setAmount(CargoBatch cb, int amount) {
if (0 == amount) {
sortedMap.remove(cb);
} else {
sortedMap.put(cb, new Integer(amount));
}
updateID++;
}
No outgoing methods.
jfreerails.world.cargo.MutableCargoBundle.size
Javadoc:
No Javadoc available
Method code:
public int size() {
return sortedMap.size();
}
No outgoing methods.
jfreerails.world.cargo.MutableCargoBundle.toImmutableCargoBundle
Javadoc:
No Javadoc available
Method code:
public ImmutableCargoBundle toImmutableCargoBundle() {
return new ImmutableCargoBundle(sortedMap);
}
No outgoing methods.
jfreerails.world.common.Activity.duration
Javadoc:
No Javadoc available
Method code:
double duration();
No outgoing methods.
jfreerails.world.common.Activity.getState
Javadoc:
No Javadoc available
Method code:
E getState(double dt);
No outgoing methods.
jfreerails.world.common.ActivityIterator.absolute2relativeTime
Javadoc:
/** * Converts an absolute time value to a time value relative to the start of * the current activity. If absoluteTime > getFinishTime(), getDuration() is * returned. */
Method code:
/**
* Converts an absolute time value to a time value relative to the start of
* the current activity. If absoluteTime > getFinishTime(), getDuration() is
* returned.
*/
double absolute2relativeTime(double absoluteTime);
No outgoing methods.
jfreerails.world.common.ActivityIterator.getActivity
Javadoc:
No Javadoc available
Method code:
Activity getActivity();
No outgoing methods.
jfreerails.world.common.ActivityIterator.getDuration
Javadoc:
No Javadoc available
Method code:
double getDuration();
No outgoing methods.
jfreerails.world.common.ActivityIterator.getFinishTime
Javadoc:
/** Returns the time the current activity ends. */
Method code:
/** Returns the time the current activity ends. */
double getFinishTime();
No outgoing methods.
jfreerails.world.common.ActivityIterator.getStartTime
Javadoc:
/** Returns the time the current activity starts. */
Method code:
/** Returns the time the current activity starts. */
double getStartTime();
No outgoing methods.
jfreerails.world.common.ActivityIterator.getState
Javadoc:
No Javadoc available
Method code:
FreerailsSerializable getState(double absoluteTime);
No outgoing methods.
jfreerails.world.common.ActivityIterator.gotoLastActivity
Javadoc:
No Javadoc available
Method code:
void gotoLastActivity();
No outgoing methods.
jfreerails.world.common.ActivityIterator.hasNext
Javadoc:
No Javadoc available
Method code:
boolean hasNext();
No outgoing methods.
jfreerails.world.common.ActivityIterator.hasPrevious
Javadoc:
No Javadoc available
Method code:
boolean hasPrevious();
No outgoing methods.
jfreerails.world.common.ActivityIterator.nextActivity
Javadoc:
No Javadoc available
Method code:
void nextActivity() throws NoSuchElementException;
No outgoing methods.
jfreerails.world.common.ActivityIterator.previousActivity
Javadoc:
No Javadoc available
Method code:
void previousActivity() throws NoSuchElementException;
No outgoing methods.
jfreerails.world.common.FlatTrackTemplate.contains
Javadoc:
/** * @param ftt * the FlatTrackTemplate which may be a subset of this * FlatTrackTemplate. * @return true if the vectors represented by this FlatTrackTemplate are a * superset of the vectors of the specified FlatTrackTemplate */
Method code:
/**
* @param ftt
* the FlatTrackTemplate which may be a subset of this
* FlatTrackTemplate.
* @return true if the vectors represented by this FlatTrackTemplate are a
* superset of the vectors of the specified FlatTrackTemplate
*/
boolean contains(FlatTrackTemplate ftt);
No outgoing methods.
jfreerails.world.common.FlatTrackTemplate.get9bitTemplate
Javadoc:
/** * @return the integer representing the vector(s) of this object. */
Method code:
/**
* @return the integer representing the vector(s) of this object.
*/
int get9bitTemplate();
No outgoing methods.
jfreerails.world.common.FreerailsPathIterator.hasNext
Javadoc:
/** * Tests whether the path has another segment. */
Method code:
/**
* Tests whether the path has another segment.
*/
boolean hasNext();
No outgoing methods.
jfreerails.world.common.FreerailsPathIterator.nextSegment
Javadoc:
/** * Gets the next segment of the path and places its coordinates in the * specified IntLine; then moves the iterator forwards by one path segment. * (The coordinates are placed the passed-in IntLine rather than a new * object to avoid the cost of object creation.) * * @param line */
Method code:
/**
* Gets the next segment of the path and places its coordinates in the
* specified IntLine; then moves the iterator forwards by one path segment.
* (The coordinates are placed the passed-in IntLine rather than a new
* object to avoid the cost of object creation.)
*
* @param line
*/
void nextSegment(IntLine line);
No outgoing methods.
jfreerails.world.common.FreerailsPathIteratorImpl.backwardsIterator
Javadoc:
No Javadoc available
Method code:
public static FreerailsPathIterator backwardsIterator(List<Point> l) {
return new FreerailsPathIteratorImpl(l, false);
}
No outgoing methods.
jfreerails.world.common.FreerailsPathIteratorImpl.forwardsIterator
Javadoc:
No Javadoc available
Method code:
public static FreerailsPathIterator forwardsIterator(List<Point> l) {
return new FreerailsPathIteratorImpl(l, true);
}
No outgoing methods.
jfreerails.world.common.FreerailsPathIteratorImpl.hasNext
Javadoc:
No Javadoc available
Method code:
public boolean hasNext() {
if (forwards) {
return (position + 1) < points.size();
}
return (position - 1) >= 0;
}
No outgoing methods.
jfreerails.world.common.FreerailsPathIteratorImpl.nextSegment
Javadoc:
No Javadoc available
Method code:
public void nextSegment(IntLine line) {
if (hasNext()) {
Point a;
Point b;
if (forwards) {
position++;
a = points.get(position - 1);
b = points.get(position);
} else {
position--;
a = points.get(position + 1);
b = points.get(position);
}
line.x1 = a.x;
line.y1 = a.y;
line.x2 = b.x;
line.y2 = b.y;
} else {
throw new NoSuchElementException();
}
}
Outgoing Methods (calls):
jfreerails.world.common.GameCalendar.getMonth
Javadoc:
/** Returns the month, 0=Jan, 1=Feb, etc. */
Method code:
/** Returns the month, 0=Jan, 1=Feb, etc. */
public int getMonth(int i) {
int ticksPerMonth = ticksPerYear / 12;
return (i % ticksPerYear) / ticksPerMonth;
}
No outgoing methods.
jfreerails.world.common.GameCalendar.getStartOfYear
Javadoc:
No Javadoc available
Method code:
public GameTime getStartOfYear(GameTime t) {
int year = getYear(t.getTicks());
int ticks = getTicks(year);
return new GameTime(ticks);
}
Outgoing Methods (calls):
jfreerails.world.common.GameCalendar.getTicks
Javadoc:
No Javadoc available
Method code:
public int getTicks(int year) {
int deltaYear = year - startYear;
return deltaYear * ticksPerYear;
}
No outgoing methods.
jfreerails.world.common.GameCalendar.getTicksPerYear
Javadoc:
No Javadoc available
Method code:
public int getTicksPerYear() {
return ticksPerYear;
}
No outgoing methods.
jfreerails.world.common.GameCalendar.getTimeOfDay
Javadoc:
/** * Returns the time of day as a string, note that a year is made up of a * representative day, so 1st June is equivalent to 12 noon. */
Method code:
/**
* Returns the time of day as a string, note that a year is made up of a
* representative day, so 1st June is equivalent to 12 noon.
*/
public String getTimeOfDay(int i) {
int ticksPerHour = ticksPerYear / 24;
int hour = ticksPerHour == 0 ? 0 : (i % ticksPerYear) / ticksPerHour;
int ticksPerMinute = ticksPerYear / (24 * 60);
int minute = ticksPerMinute == 0 ? 0 : (i % (ticksPerMinute * 60));
return decimalFormat.format(hour) + ":" + decimalFormat.format(minute);
}
No outgoing methods.
jfreerails.world.common.GameCalendar.getYear
Javadoc:
No Javadoc available
Method code:
public int getYear(int ticks) {
return startYear + (ticks / ticksPerYear);
}
No outgoing methods.
jfreerails.world.common.GameCalendar.getYearAndMonth
Javadoc:
No Javadoc available
Method code:
public String getYearAndMonth(int i) {
int month = getMonth(i);
String monthAbrev = null;
switch (month) {
case 0: {
monthAbrev = "Jan";
break;
}
case 1: {
monthAbrev = "Feb";
break;
}
case 2: {
monthAbrev = "Mar";
break;
}
case 3: {
monthAbrev = "Apr";
break;
}
case 4: {
monthAbrev = "May";
break;
}
case 5: {
monthAbrev = "Jun";
break;
}
case 6: {
monthAbrev = "Jul";
break;
}
case 7: {
monthAbrev = "Aug";
break;
}
case 8: {
monthAbrev = "Sep";
break;
}
case 9: {
monthAbrev = "Oct";
break;
}
case 10: {
monthAbrev = "Nov";
break;
}
case 11: {
monthAbrev = "Dec";
break;
}
}
return monthAbrev + " " + getYearAsString(i);
}
Outgoing Methods (calls):
jfreerails.world.common.GameCalendar.getYearAsString
Javadoc:
No Javadoc available
Method code:
public String getYearAsString(int ticks) {
int i = getYear(ticks);
return String.valueOf(i);
}
Outgoing Methods (calls):
jfreerails.world.common.GameCalenderTest.testGetTimeOfDay
Javadoc:
No Javadoc available
Method code:
public void testGetTimeOfDay() {
GameCalendar gc = new GameCalendar(24, 1900);
assertEquals("00:00", gc.getTimeOfDay(0));
assertEquals("01:00", gc.getTimeOfDay(1));
assertEquals("15:00", gc.getTimeOfDay(15));
gc = new GameCalendar(24 * 60, 1900);
assertEquals("00:00", gc.getTimeOfDay(0));
assertEquals("00:10", gc.getTimeOfDay(10));
assertEquals("05:10", gc.getTimeOfDay(310));
}
Outgoing Methods (calls):
jfreerails.world.common.GameCalenderTest.testGetYear
Javadoc:
No Javadoc available
Method code:
public void testGetYear() {
GameCalendar gc = new GameCalendar(10, 1900);
assertEquals("1900", gc.getYearAsString(0));
assertEquals("1900", gc.getYearAsString(5));
assertEquals("1901", gc.getYearAsString(10));
assertEquals("1950", gc.getYearAsString(505));
}
Outgoing Methods (calls):
jfreerails.world.common.GameCalenderTest.testGetYearAndMonth
Javadoc:
No Javadoc available
Method code:
public void testGetYearAndMonth() {
GameCalendar gc = new GameCalendar(12, 1900);
assertEquals("Jan 1900", gc.getYearAndMonth(0));
assertEquals("Feb 1900", gc.getYearAndMonth(1));
assertEquals("Mar 1900", gc.getYearAndMonth(2));
assertEquals("Mar 1901", gc.getYearAndMonth(14));
}
Outgoing Methods (calls):
jfreerails.world.common.GameSpeed.getSpeed
Javadoc:
No Javadoc available
Method code:
public int getSpeed() {
return speed;
}
No outgoing methods.
jfreerails.world.common.GameSpeed.isPaused
Javadoc:
No Javadoc available
Method code:
public boolean isPaused(){
return speed < 1;
}
No outgoing methods.
jfreerails.world.common.GameTime.compareTo
Javadoc:
/** * Compares two GameTimes for ordering. * * @param t * @return 0 if t is equal to this GameTime; a value less than 0 if this * GameTime is before t; and a value greater than 0 if this GameTime * is after t. */
Method code:
/**
* Compares two GameTimes for ordering.
*
* @param t
* @return 0 if t is equal to this GameTime; a value less than 0 if this
* GameTime is before t; and a value greater than 0 if this GameTime
* is after t.
*/
public int compareTo(GameTime t) {
return ticks - t.ticks;
}
No outgoing methods.
jfreerails.world.common.GameTime.getTicks
Javadoc:
No Javadoc available
Method code:
public int getTicks() {
return ticks;
}
No outgoing methods.
jfreerails.world.common.GameTime.nextTick
Javadoc:
No Javadoc available
Method code:
public GameTime nextTick() {
return new GameTime(ticks + 1);
}
No outgoing methods.
jfreerails.world.common.ImHashSet.contains
Javadoc:
No Javadoc available
Method code:
public boolean contains(E e) {
return hashSet.contains(e);
}
No outgoing methods.
jfreerails.world.common.ImHashSet.iterator
Javadoc:
No Javadoc available
Method code:
public Iterator<E> iterator() {
return new Iterator<E>() {
Iterator<E> it = hashSet.iterator();
public boolean hasNext() {
return it.hasNext();
}
public E next() {
return it.next();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
No outgoing methods.
jfreerails.world.common.ImInts.append
Javadoc:
No Javadoc available
Method code:
public ImInts append(int... extra) {
int[] newInts = new int[ints.length + extra.length];
System.arraycopy(ints, 0, newInts, 0, ints.length);
System.arraycopy(extra, 0, newInts, ints.length, extra.length);
return new ImInts(newInts);
}
No outgoing methods.
jfreerails.world.common.ImInts.fromBoolean
Javadoc:
No Javadoc available
Method code:
public static ImInts fromBoolean(boolean... i) {
int[] ii = new int[i.length];
for (int j = 0; j < i.length; j++) {
ii[j] = i[j] ? 1 : 0;
}
return new ImInts(ii);
}
No outgoing methods.
jfreerails.world.common.ImInts.get
Javadoc:
No Javadoc available
Method code:
public int get(int i) {
return ints[i];
}
No outgoing methods.
jfreerails.world.common.ImInts.removeLast
Javadoc:
No Javadoc available
Method code:
public ImInts removeLast() {
int[] newInts = new int[ints.length - 1];
System.arraycopy(ints, 0, newInts, 0, newInts.length);
return new ImInts(newInts);
}
No outgoing methods.
jfreerails.world.common.ImInts.size
Javadoc:
No Javadoc available
Method code:
public int size() {
return ints.length;
}
No outgoing methods.
jfreerails.world.common.ImInts.sum
Javadoc:
/** Returns the sum of the ints stored in the list.*/
Method code:
/** Returns the sum of the ints stored in the list.*/
public int sum(){
int sum = 0;
for (int i = 0; i < ints.length; i++) {
sum+=ints[i];
}
return sum;
}
No outgoing methods.
jfreerails.world.common.ImIntsTest.testAppend
Javadoc:
No Javadoc available
Method code:
/*
* Test method for 'jfreerails.world.common.ImInts.append(int...)'
*/
public void testAppend() {
int[] a = { 1, 2, 3 };
int[] b = { 4, 5, 6, 7 };
int[] c = { 1, 2, 3, 4, 5, 6, 7 };
ImInts ai = new ImInts(a);
ImInts ci = new ImInts(c);
assertFalse(ci.equals(ai));
assertEquals(ci, ai.append(b));
}
Outgoing Methods (calls):
jfreerails.world.common.ImIntsTest.testEquals
Javadoc:
No Javadoc available
Method code:
public void testEquals(){
int[] a = { 1, 2, 3 };
int[] b = { 1, 2, 3 };
ImInts ai = new ImInts(a);
ImInts bi = new ImInts(b);
assertEquals(ai, bi);
ImInts ci = new ImInts(1, 2, 3 );
assertEquals(ai, ci);
}
No outgoing methods.
jfreerails.world.common.ImIntsTest.testRemoveLast
Javadoc:
No Javadoc available
Method code:
public void testRemoveLast(){
//Test method does not change original
ImInts original = new ImInts(1,2, 3, 4);
ImInts clone = (ImInts) Utils.cloneBySerialisation(original);
assertEquals(original, clone);
original.removeLast();
assertEquals(original, clone);
ImInts actual, expected;
actual = (new ImInts( 1, 2, 3)).removeLast();
expected = new ImInts(1,2);
assertEquals(expected, actual);
actual = (new ImInts( 1, 2)).removeLast();
expected = new ImInts(1);
assertEquals(expected, actual);
actual = (new ImInts( 1, 2, 4, 3)).removeLast();
expected = new ImInts(1, 2, 4);
assertEquals(expected, actual);
}
Outgoing Methods (calls):
jfreerails.world.common.ImList.checkForNulls
Javadoc:
/** * Checks each element in the internal array for null values. * If any element is found to be null, a NullPointerException is thrown. * * @throws NullPointerException if any element in the array is null. */
Method code:
public void checkForNulls() throws NullPointerException {
for (int i = 0; i < elementData.length; i++) {
if (null == elementData[i])
throw new NullPointerException();
}
}
No outgoing methods.
jfreerails.world.common.ImList.get
Javadoc:
No Javadoc available
Method code:
public E get(int i) {
return elementData[i];
}
No outgoing methods.
jfreerails.world.common.ImList.size
Javadoc:
No Javadoc available
Method code:
public int size() {
return elementData.length;
}
No outgoing methods.
jfreerails.world.common.ImPoint.compareTo
Javadoc:
No Javadoc available
Method code:
public int compareTo(ImPoint o) {
if (o.y != y)
return y - o.y;
else
return x - o.x;
}
No outgoing methods.
jfreerails.world.common.ImPoint.toPoint
Javadoc:
/** * Converts this ImPoint instance to a Point object with the same coordinates. * * @return a new Point instance with the same x and y values as this ImPoint. */
Method code:
public Point toPoint() {
return new Point(x, y);
}
No outgoing methods.
jfreerails.world.common.ImSet.contains
Javadoc:
No Javadoc available
Method code:
public boolean contains(E element) {
return hashSet.contains(element);
}
No outgoing methods.
jfreerails.world.common.ImStringList.get
Javadoc:
No Javadoc available
Method code:
public String get(int i) {
return strings[i];
}
No outgoing methods.
jfreerails.world.common.ImStringList.size
Javadoc:
No Javadoc available
Method code:
public int size() {
return strings.length;
}
No outgoing methods.
jfreerails.world.common.IntLine.getLength
Javadoc:
/** * @return the length of the line */
Method code:
/**
* @return the length of the line
*/
public double getLength() {
int sumOfSquares = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
if(sumOfSquares < MAX_SQUAREROOTS) {
return squareRoots[sumOfSquares];
}
return Math.sqrt(sumOfSquares);
}
No outgoing methods.
jfreerails.world.common.Money.changeSign
Javadoc:
No Javadoc available
Method code:
public Money changeSign() {
return new Money(-amount);
}
No outgoing methods.
jfreerails.world.common.Money.getAmount
Javadoc:
No Javadoc available
Method code:
public long getAmount() {
return amount;
}
No outgoing methods.
jfreerails.world.common.PositionOnTrack.cameFrom
Javadoc:
/** * @return The direction the entity came from. */
Method code:
/**
* @return The direction the entity came from.
*/
public Step cameFrom() {
return cameFrom;
}
No outgoing methods.
jfreerails.world.common.PositionOnTrack.createComingFrom
Javadoc:
/** * Creates a new PositionOnTrack instance representing a position on the rail track. * The direction parameter indicates the direction from which the position is approached. * * @param x the x-coordinate of the position on the track * @param y the y-coordinate of the position on the track * @param direction the Step enum value indicating the direction from which the position is coming * @return a new PositionOnTrack instance with the specified coordinates and direction */
Method code:
public static PositionOnTrack createComingFrom(int x, int y, Step direction) {
return new PositionOnTrack(x, y, direction);
}
No outgoing methods.
jfreerails.world.common.PositionOnTrack.createFacing
Javadoc:
No Javadoc available
Method code:
public static PositionOnTrack createFacing(int x, int y, Step direction) {
return new PositionOnTrack(x, y, direction.getOpposite());
}
Outgoing Methods (calls):
jfreerails.world.common.PositionOnTrack.facing
Javadoc:
/** * @return The direction the entity is facing. */
Method code:
/**
* @return The direction the entity is facing.
*/
public Step facing() {
return cameFrom.getOpposite();
}
Outgoing Methods (calls):
jfreerails.world.common.PositionOnTrack.fromInts
Javadoc:
No Javadoc available
Method code:
public static PositionOnTrack[] fromInts(int[] ints) {
PositionOnTrack[] returnValue = new PositionOnTrack[ints.length];
for (int i = 0; i < ints.length; i++) {
PositionOnTrack p = new PositionOnTrack(ints[i]);
returnValue[i] = p;
}
return returnValue;
}
No outgoing methods.
jfreerails.world.common.PositionOnTrack.getOpposite
Javadoc:
/** * @return the position on the track which is in the opposite direction. */
Method code:
/**
* @return the position on the track which is in the opposite direction.
*/
public PositionOnTrack getOpposite() {
int newX = this.getX() - this.cameFrom.deltaX;
int newY = this.getY() - this.cameFrom.deltaY;
Step newDirection = this.cameFrom.getOpposite();
return createComingFrom(newX, newY, newDirection);
}
Outgoing Methods (calls):
jfreerails.world.common.PositionOnTrack.getX
Javadoc:
No Javadoc available
Method code:
public int getX() {
return x;
}
No outgoing methods.
jfreerails.world.common.PositionOnTrack.getY
Javadoc:
No Javadoc available
Method code:
public int getY() {
return y;
}
No outgoing methods.
jfreerails.world.common.PositionOnTrack.move
Javadoc:
No Javadoc available
Method code:
public void move(Step step) {
this.x += step.deltaX;
this.y += step.deltaY;
this.cameFrom = step.getOpposite();
}
Outgoing Methods (calls):
jfreerails.world.common.PositionOnTrack.setCameFrom
Javadoc:
No Javadoc available
Method code:
public void setCameFrom(Step v) {
this.cameFrom = v;
}
No outgoing methods.
jfreerails.world.common.PositionOnTrack.setFacing
Javadoc:
No Javadoc available
Method code:
public void setFacing(Step v) {
this.cameFrom = v.getOpposite();
}
Outgoing Methods (calls):
jfreerails.world.common.PositionOnTrack.setValuesFromInt
Javadoc:
No Javadoc available
Method code:
public void setValuesFromInt(int i) {
x = i & MAX_COORDINATE;
int shiftedY = i & (MAX_COORDINATE << BITS_FOR_COORDINATE);
y = shiftedY >> BITS_FOR_COORDINATE;
int shiftedDirection = i & (MAX_DIRECTION << (2 * BITS_FOR_COORDINATE));
int directionAsInt = shiftedDirection >> (2 * BITS_FOR_COORDINATE);
cameFrom = Step.getInstance(directionAsInt);
}
Outgoing Methods (calls):
jfreerails.world.common.PositionOnTrack.setX
Javadoc:
No Javadoc available
Method code:
public void setX(int x) {
this.x = x;
}
No outgoing methods.
jfreerails.world.common.PositionOnTrack.setY
Javadoc:
No Javadoc available
Method code:
public void setY(int y) {
this.y = y;
}
No outgoing methods.
jfreerails.world.common.PositionOnTrack.toInt
Javadoc:
/** * @return an integer representing this PositionOnTrack object */
Method code:
/**
* @return an integer representing this PositionOnTrack object
*/
public int toInt() {
int i = x | (y << BITS_FOR_COORDINATE);
int directionAsInt = cameFrom.getID();
int shiftedDirection = (directionAsInt << (2 * BITS_FOR_COORDINATE));
i = i | shiftedDirection;
return i;
}
Outgoing Methods (calls):
jfreerails.world.common.PositionOnTrack.toInts
Javadoc:
No Javadoc available
Method code:
public static int[] toInts(PositionOnTrack[] pos) {
int[] returnValue = new int[pos.length];
for (int i = 0; i < pos.length; i++) {
returnValue[i] = pos[i].toInt();
}
return returnValue;
}
Outgoing Methods (calls):
jfreerails.world.common.PositionOnTrackTest.assertException
Javadoc:
No Javadoc available
Method code:
private void assertException(int x, int y, Step v) {
try {
PositionOnTrack.createComingFrom(x, y, v);
assertTrue(false);
} catch (Exception e) {
}
}
Outgoing Methods (calls):
jfreerails.world.common.PositionOnTrackTest.assertNoException
Javadoc:
No Javadoc available
Method code:
private void assertNoException(int x, int y, Step v) {
try {
PositionOnTrack.createComingFrom(x, y, v);
} catch (Exception e) {
assertTrue(false);
}
}
Outgoing Methods (calls):
jfreerails.world.common.PositionOnTrackTest.testEqualsObject
Javadoc:
No Javadoc available
Method code:
/*
* Test for boolean equals(Object)
*/
public void testEqualsObject() {
PositionOnTrack p1 = PositionOnTrack.createComingFrom(10, 20,
Step.NORTH);
PositionOnTrack p2 = PositionOnTrack.createComingFrom(10, 20,
Step.NORTH);
assertEquals(p1, p2);
p1 = PositionOnTrack.createComingFrom(10, 50, Step.NORTH);
p2 = PositionOnTrack.createComingFrom(10, 20, Step.NORTH);
assertTrue(!p1.equals(p2));
}
Outgoing Methods (calls):
jfreerails.world.common.PositionOnTrackTest.testGetOpposite
Javadoc:
No Javadoc available
Method code:
public void testGetOpposite() {
PositionOnTrack p1 = PositionOnTrack.createComingFrom(10, 10,
Step.NORTH);
PositionOnTrack p2 = p1.getOpposite();
assertNotNull(p2);
PositionOnTrack p3 = PositionOnTrack.createComingFrom(10, 11,
Step.SOUTH);
assertEquals(p3, p2);
}
Outgoing Methods (calls):
jfreerails.world.common.PositionOnTrackTest.testSetValuesFromInt
Javadoc:
No Javadoc available
Method code:
public void testSetValuesFromInt() {
PositionOnTrack p1 = PositionOnTrack.createComingFrom(10, 20,
Step.NORTH);
int i = p1.toInt();
PositionOnTrack p2 = PositionOnTrack
.createComingFrom(60, 70, Step.EAST);
assertTrue(!p1.equals(p2));
p2.setValuesFromInt(i);
assertEquals(p1, p2);
Step v = Step.getInstance(7); // 7 is the
// maximum
// vector
// number.
p1 = PositionOnTrack.createComingFrom(PositionOnTrack.MAX_COORDINATE,
PositionOnTrack.MAX_COORDINATE, v);
i = p1.toInt();
}
Outgoing Methods (calls):
jfreerails.world.common.PositionOnTrackTest.testToInt
Javadoc:
No Javadoc available
Method code:
public void testToInt() {
PositionOnTrack p1 = PositionOnTrack.createComingFrom(10, 20,
Step.NORTH);
PositionOnTrack p2 = PositionOnTrack.createComingFrom(10, 30,
Step.NORTH);
assertTrue(p1.toInt() != p2.toInt());
}
Outgoing Methods (calls):
jfreerails.world.common.PositionOnTrackTest.testValidation
Javadoc:
No Javadoc available
Method code:
public void testValidation() {
assertTrue(PositionOnTrack.MAX_COORDINATE < 70000);
assertTrue(PositionOnTrack.MAX_COORDINATE > 10000);
assertEquals(PositionOnTrack.MAX_DIRECTION, 7);
assertNoException(0, 0, Step.EAST);
assertNoException(PositionOnTrack.MAX_COORDINATE,
PositionOnTrack.MAX_COORDINATE, Step.NORTH_WEST);
assertException(-1, 0, Step.EAST);
assertException(0, -1, Step.EAST);
assertException(PositionOnTrack.MAX_COORDINATE + 1,
PositionOnTrack.MAX_COORDINATE, Step.NORTH_WEST);
assertException(PositionOnTrack.MAX_COORDINATE,
PositionOnTrack.MAX_COORDINATE + 1, Step.NORTH_WEST);
}
Outgoing Methods (calls):
jfreerails.world.common.Step.checkValidity
Javadoc:
/** * Returns true if the values passed could be used to create a valid vector. */
Method code:
/**
* Returns true if the values passed could be used to create a valid vector.
*/
public static boolean checkValidity(int x, int y) {
if ((((x < -1) || (x > 1)) || ((y < -1) || (y > 1)))
|| ((x == 0) && (y == 0))) {
return false;
}
return true;
}
No outgoing methods.
jfreerails.world.common.Step.contains
Javadoc:
No Javadoc available
Method code:
public boolean contains(FlatTrackTemplate ftt) {
if (ftt.get9bitTemplate() == this.flatTrackTemplate) {
return true;
}
return false;
}
Outgoing Methods (calls):
jfreerails.world.common.Step.createRelocatedPoint
Javadoc:
No Javadoc available
Method code:
public ImPoint createRelocatedPoint(ImPoint from) {
return new ImPoint(from.x + deltaX, from.y + deltaY);
}
No outgoing methods.
jfreerails.world.common.Step.get8bitTemplate
Javadoc:
No Javadoc available
Method code:
public int get8bitTemplate() {
return 1 << this.getID();
}
Outgoing Methods (calls):
jfreerails.world.common.Step.get9bitTemplate
Javadoc:
No Javadoc available
Method code:
public int get9bitTemplate() {
return flatTrackTemplate;
}
No outgoing methods.
jfreerails.world.common.Step.getDirection
Javadoc:
/** * * @return compass bearing in radians. */
Method code:
/**
*
* @return compass bearing in radians.
*/
public double getDirection() {
int i = 0;
while (this != list[i]) {
i++;
}
return 2 * Math.PI / 8 * i;
}
No outgoing methods.
jfreerails.world.common.Step.getDx
Javadoc:
/** Returns the X component of the vector. */
Method code:
/** Returns the X component of the vector. */
public int getDx() {
return deltaX;
}
No outgoing methods.
jfreerails.world.common.Step.getDy
Javadoc:
/** Returns the Y component of the vector. */
Method code:
/** Returns the Y component of the vector. */
public int getDy() {
return deltaY;
}
No outgoing methods.
jfreerails.world.common.Step.getID
Javadoc:
/** * @return a number representing the compass point this vector indicates, * with 0 representing North, 1 NorthEast, 2 East and so on. */
Method code:
/**
* @return a number representing the compass point this vector indicates,
* with 0 representing North, 1 NorthEast, 2 East and so on.
*/
public int getID() {
int i = 0;
while (this != list[i]) {
i++;
}
return i;
}
No outgoing methods.
jfreerails.world.common.Step.getInstance
Javadoc:
No Javadoc available
Method code:
public static Step getInstance(int dx, int dy) {
if ((((dx < -1) || (dx > 1)) || ((dy < -1) || (dy > 1)))
|| ((dx == 0) && (dy == 0))) {
throw new IllegalArgumentException(
dx
+ " and "
+ dy
+ ": The values passed both must be integers in the range -1 to 1, and not both equal 0.");
}
return vectors[dx + 1][dy + 1];
}
No outgoing methods.
jfreerails.world.common.Step.getLength
Javadoc:
/** * @return the length of this vector. Each tile is 100 units x 100 units. */
Method code:
/**
* @return the length of this vector. Each tile is 100 units x 100 units.
*/
public double getLength() {
return length;
}
No outgoing methods.
jfreerails.world.common.Step.getList
Javadoc:
/** * @return a copy of the list of 8 OneTileMoveVectors going clockwise from * North. */
Method code:
/**
* @return a copy of the list of 8 OneTileMoveVectors going clockwise from
* North.
*/
public static Step[] getList() {
return list.clone(); // defensive copy.
}
Outgoing Methods (calls):
jfreerails.world.common.Step.getNearestVector
Javadoc:
/** * @return the OneTileMoveVector nearest in orientation to the specified dx, * dy */
Method code:
/**
* @return the OneTileMoveVector nearest in orientation to the specified dx,
* dy
*/
public static Step getNearestVector(int dx, int dy) {
if (0 == dx * dy) {
if (dx > 0) {
return EAST;
} else if (dx != 0) {
return WEST;
} else if (dy > 0) {
return SOUTH;
} else {
return NORTH;
}
}
double gradient = dy;
gradient = gradient / dx;
double B = 2;
double A = 0.5;
double C = -2;
double D = -0.5;
if (gradient > B) {
if (dy < 0) {
return NORTH;
}
return SOUTH;
} else if (gradient > A) {
if (dy > 0) {
return SOUTH_EAST;
}
return NORTH_WEST;
} else if (gradient > D) {
if (dx > 0) {
return EAST;
}
return WEST;
} else if (gradient > C) {
if (dx < 0) {
return SOUTH_WEST;
}
return NORTH_EAST;
} else {
if (dy > 0) {
return SOUTH;
}
return NORTH;
}
}
No outgoing methods.
jfreerails.world.common.Step.getOpposite
Javadoc:
/** * Returns a new oneTileMoveVector whose direction is opposite to that the * current one. * * @return A oneTileMoveVector. */
Method code:
/**
* Returns a new oneTileMoveVector whose direction is opposite to that the
* current one.
*
* @return A oneTileMoveVector.
*/
public Step getOpposite() {
return getInstance(this.deltaX * -1, this.deltaY * -1);
}
Outgoing Methods (calls):
jfreerails.world.common.Step.isDiagonal
Javadoc:
No Javadoc available
Method code:
public boolean isDiagonal() {
return 0 != deltaX * deltaY;
}
No outgoing methods.
jfreerails.world.common.Step.move
Javadoc:
No Javadoc available
Method code:
public static ImPoint move(ImPoint p, Step... path) {
int x = p.x;
int y = p.y;
for (Step v : path) {
x += v.deltaX;
y += v.deltaY;
}
return new ImPoint(x, y);
}
No outgoing methods.
jfreerails.world.common.Step.readResolve
Javadoc:
No Javadoc available
Method code:
private Object readResolve() throws ObjectStreamException {
return Step.getInstance(this.deltaX, this.deltaY);
}
Outgoing Methods (calls):
jfreerails.world.common.Step.setupVectors
Javadoc:
No Javadoc available
Method code:
private static Step[][] setupVectors() {
int t = 1;
Step[][] tvectors = new Step[3][3];
for (int y = -1; y <= 1; y++) {
for (int x = -1; x <= 1; x++) {
if ((0 != x) || (0 != y)) {
tvectors[x + 1][y + 1] = new Step(x, y, t);
}
t = t << 1;
}
}
return tvectors;
}
No outgoing methods.
jfreerails.world.common.Step.toAbrvString
Javadoc:
No Javadoc available
Method code:
public String toAbrvString() {
String name;
switch (deltaY) {
case 1:
name = "s";
break;
case -1:
name = "n";
break;
default:
name = "";
break;
}
switch (deltaX) {
case 1:
name += "e";
break;
case -1:
name += "w";
break;
default:
break;
}
return name;
}
No outgoing methods.
jfreerails.world.common.StepTest.assertNearest
Javadoc:
No Javadoc available
Method code:
private void assertNearest(Step v, int dx, int dy) {
Step v2 = Step.getNearestVector(dx, dy);
assertEquals(v, v2);
}
Outgoing Methods (calls):
jfreerails.world.common.StepTest.testGetDirection
Javadoc:
No Javadoc available
Method code:
public void testGetDirection() {
double d = 0;
assertTrue(d == n.getDirection());
d = 2 * Math.PI / 8 * 1;
assertTrue(d == ne.getDirection());
}
Outgoing Methods (calls):
jfreerails.world.common.StepTest.testGetNearestVector
Javadoc:
No Javadoc available
Method code:
public void testGetNearestVector() {
// Each vector should be the nearest to itself!
Step[] vectors = Step.getList();
for (int i = 0; i < vectors.length; i++) {
Step v = vectors[i];
Step v2 = Step.getNearestVector(v.deltaX, v.deltaY);
assertEquals(v, v2);
}
assertNearest(n, 0, -1);
assertNearest(n, 0, -99);
assertNearest(n, 2, -5);
assertNearest(n, -2, -5);
assertNearest(s, 2, 5);
assertNearest(w, -5, -1);
assertNearest(sw, -4, 3);
assertNearest(ne, 10, -6);
assertNearest(ne, 10, -6);
}
Outgoing Methods (calls):
jfreerails.world.common.StepTest.testGetNewTemplateNumber
Javadoc:
No Javadoc available
Method code:
public void testGetNewTemplateNumber() {
assertEquals(Step.NORTH.get8bitTemplate(), 1);
assertEquals(Step.NORTH_EAST.get8bitTemplate(), 2);
assertEquals(Step.EAST.get8bitTemplate(), 4);
}
Outgoing Methods (calls):
jfreerails.world.player.FreerailsPrincipal.getWorldIndex
Javadoc:
/** * returns -1 if it's not a player * @return the index in the world structures */
Method code:
/**
* returns -1 if it's not a player
* @return the index in the world structures
*/
public int getWorldIndex() {
return worldIndex;
}
No outgoing methods.
jfreerails.world.player.Player.getName
Javadoc:
No Javadoc available
Method code:
public String getName() {
return name;
}
No outgoing methods.
jfreerails.world.player.Player.getPrincipal
Javadoc:
No Javadoc available
Method code:
public FreerailsPrincipal getPrincipal() {
return principal;
}
No outgoing methods.
jfreerails.world.player.Player.loadSession
Javadoc:
/** * Called by the client to reconstitute the data from a saved game. */
Method code:
/**
* Called by the client to reconstitute the data from a saved game.
*/
public void loadSession(ObjectInputStream in) throws IOException {
// try {
// privateData = (PrivateData) in.readObject();
// } catch (ClassNotFoundException e) {
// throw new IOException("Couldn't find class:" + e);
// }
}
No outgoing methods.
jfreerails.world.player.Player.saveSession
Javadoc:
/** * TODO save this player's private data so that they can be re-connected to * the server at a later point in time. */
Method code:
/**
* TODO save this player's private data so that they can be re-connected to
* the server at a later point in time.
*/
public void saveSession(ObjectOutputStream out) throws IOException {
// out.writeObject(privateData);
}
No outgoing methods.
jfreerails.world.player.PlayerPrincipal.getId
Javadoc:
/** * @return an integer unique to this PlayerPrincipal */
Method code:
/**
* @return an integer unique to this PlayerPrincipal
*/
public int getId() {
return id;
}
No outgoing methods.
jfreerails.world.player.PlayerPrincipal.getName
Javadoc:
No Javadoc available
Method code:
public String getName() {
return name;
}
No outgoing methods.
jfreerails.world.player.WorldPrincipal.getName
Javadoc:
No Javadoc available
Method code:
public String getName() {
return principalName;
}
No outgoing methods.
jfreerails.world.station.ConvertedAtStation.emptyConversionArray
Javadoc:
No Javadoc available
Method code:
public static int[] emptyConversionArray(int numberOfCargoTypes) {
int[] convertedTo = new int[numberOfCargoTypes];
for (int i = 0; i < numberOfCargoTypes; i++) {
convertedTo[i] = NOT_CONVERTED;
}
return convertedTo;
}
No outgoing methods.
jfreerails.world.station.ConvertedAtStation.emptyInstance
Javadoc:
No Javadoc available
Method code:
public static ConvertedAtStation emptyInstance(int numberOfCargoTypes) {
int[] convertedTo = emptyConversionArray(numberOfCargoTypes);
return new ConvertedAtStation(convertedTo);
}
Outgoing Methods (calls):
jfreerails.world.station.ConvertedAtStation.getConversion
Javadoc:
No Javadoc available
Method code:
public int getConversion(int cargoNumber) {
return convertedTo.get(cargoNumber);
}
Outgoing Methods (calls):
jfreerails.world.station.ConvertedAtStation.isCargoConverted
Javadoc:
No Javadoc available
Method code:
public boolean isCargoConverted(int cargoNumber) {
if (NOT_CONVERTED == convertedTo.get(cargoNumber)) {
return false;
}
return true;
}
Outgoing Methods (calls):
jfreerails.world.station.Demand4Cargo.isCargoDemanded
Javadoc:
No Javadoc available
Method code:
public boolean isCargoDemanded(int cargoNumber) {
return demand.get(cargoNumber) == 1;
}
Outgoing Methods (calls):
jfreerails.world.station.PlannedTrain.getEngineType
Javadoc:
No Javadoc available
Method code:
public int getEngineType() {
return engineType;
}
No outgoing methods.
jfreerails.world.station.PlannedTrain.getWagonTypes
Javadoc:
No Javadoc available
Method code:
public ImInts getWagonTypes() {
return wagonTypes;
}
No outgoing methods.
jfreerails.world.station.StationModel.getCargoBundleID
Javadoc:
No Javadoc available
Method code:
public int getCargoBundleID() {
return cargoBundleNumber;
}
No outgoing methods.
jfreerails.world.station.StationModel.getConverted
Javadoc:
No Javadoc available
Method code:
public ConvertedAtStation getConverted() {
return converted;
}
No outgoing methods.
jfreerails.world.station.StationModel.getDemand
Javadoc:
No Javadoc available
Method code:
public Demand4Cargo getDemand() {
return demand;
}
No outgoing methods.
jfreerails.world.station.StationModel.getLocation
Javadoc:
No Javadoc available
Method code:
public ImPoint getLocation(){
return new ImPoint(x, y);
}
No outgoing methods.
jfreerails.world.station.StationModel.getProduction
Javadoc:
No Javadoc available
Method code:
public ImList<PlannedTrain> getProduction() {
return production;
}
No outgoing methods.
jfreerails.world.station.StationModel.getStationName
Javadoc:
No Javadoc available
Method code:
public String getStationName() {
return name;
}
No outgoing methods.
jfreerails.world.station.StationModel.getStationX
Javadoc:
No Javadoc available
Method code:
public int getStationX() {
return x;
}
No outgoing methods.
jfreerails.world.station.StationModel.getStationY
Javadoc:
No Javadoc available
Method code:
public int getStationY() {
return y;
}
No outgoing methods.
jfreerails.world.station.StationModel.getSupply
Javadoc:
/** * Returns the SupplyAtStation object representing the supply associated with this station. * * @return the SupplyAtStation instance associated with the station. */
Method code:
public SupplyAtStation getSupply() {
return supply;
}
No outgoing methods.
jfreerails.world.station.SupplyAtStation.getSupply
Javadoc:
/** * Returns the number of car loads of the specified cargo that the station * supplies per year. */
Method code:
/**
* Returns the number of car loads of the specified cargo that the station
* supplies per year.
*/
public int getSupply(int cargoType) {
return supply.get(cargoType);
}
Outgoing Methods (calls):
jfreerails.world.terrain.CityModel.getCityName
Javadoc:
No Javadoc available
Method code:
public String getCityName() {
return name;
}
No outgoing methods.
jfreerails.world.terrain.CityModel.getCityX
Javadoc:
No Javadoc available
Method code:
public int getCityX() {
return x;
}
No outgoing methods.
jfreerails.world.terrain.CityModel.getCityY
Javadoc:
No Javadoc available
Method code:
public int getCityY() {
return y;
}
No outgoing methods.
jfreerails.world.terrain.CityModel.getLocation
Javadoc:
No Javadoc available
Method code:
public ImPoint getLocation(){
return new ImPoint(x, y);
}
No outgoing methods.
jfreerails.world.terrain.Consumption.getCargoType
Javadoc:
No Javadoc available
Method code:
public int getCargoType() {
return cargoType;
}
No outgoing methods.
jfreerails.world.terrain.Consumption.getPrerequisite
Javadoc:
No Javadoc available
Method code:
public int getPrerequisite() {
return prerequisite;
}
No outgoing methods.
jfreerails.world.terrain.Conversion.getInput
Javadoc:
No Javadoc available
Method code:
public int getInput() {
return input;
}
No outgoing methods.
jfreerails.world.terrain.Conversion.getOutput
Javadoc:
No Javadoc available
Method code:
public int getOutput() {
return output;
}
No outgoing methods.
jfreerails.world.terrain.MiscTest.assertDifferent
Javadoc:
No Javadoc available
Method code:
private void assertDifferent(Object a, Object b) {
assertFalse(a.equals(b));
assertFalse(a.hashCode() == b.hashCode());
}
No outgoing methods.
jfreerails.world.terrain.MiscTest.testCityModel
Javadoc:
No Javadoc available
Method code:
public void testCityModel() {
CityModel cm1 = new CityModel("London", 20, 70);
CityModel cm2 = new CityModel("Cardiff", 20, 70);
testHashCodeAndEquals(cm1);
testHashCodeAndEquals(cm2);
assertDifferent(cm1, cm2);
}
Outgoing Methods (calls):
jfreerails.world.terrain.MiscTest.testHashCodeAndEquals
Javadoc:
No Javadoc available
Method code:
private void testHashCodeAndEquals(Serializable a) {
Serializable copy = Utils.cloneBySerialisation(a);
assertEquals(a, a);
assertEquals(a, copy);
assertEquals(a.hashCode(), copy.hashCode());
}
Outgoing Methods (calls):
jfreerails.world.terrain.MiscTest.testTileTypeImpl
Javadoc:
No Javadoc available
Method code:
public void testTileTypeImpl() {
Production[] prod = { new Production(69, 10) };
Consumption[] cons = { new Consumption(4, 4), new Consumption(4, 5) };
Conversion[] conv = { new Conversion(50, 30) };
testHashCodeAndEquals(prod[0]);
testHashCodeAndEquals(cons[0]);
testHashCodeAndEquals(conv[0]);
TileTypeImpl tt = new TileTypeImpl(0, Category.Country, "Grassland",
100, prod, cons, conv, 10);
testHashCodeAndEquals(tt);
Conversion[] conv2 = { new Conversion(5, 30) };
TileTypeImpl tt2 = new TileTypeImpl(0, Category.Country, "Grassland",
100, prod, cons, conv2, 10);
assertFalse(tt.equals(tt2));
}
Outgoing Methods (calls):
jfreerails.world.terrain.NullTerrainType.getBuildCost
Javadoc:
No Javadoc available
Method code:
public Money getBuildCost() {
return new Money(0);
}
No outgoing methods.
jfreerails.world.terrain.NullTerrainType.getCategory
Javadoc:
No Javadoc available
Method code:
public Category getCategory() {
return Category.Country;
}
No outgoing methods.
jfreerails.world.terrain.NullTerrainType.getConsumption
Javadoc:
No Javadoc available
Method code:
public ImList<Consumption> getConsumption() {
return new ImList<Consumption>();
}
No outgoing methods.
jfreerails.world.terrain.NullTerrainType.getConversion
Javadoc:
No Javadoc available
Method code:
public ImList<Conversion> getConversion() {
return new ImList<Conversion>();
}
No outgoing methods.
jfreerails.world.terrain.NullTerrainType.getDisplayName
Javadoc:
No Javadoc available
Method code:
public String getDisplayName() {
return "";
}
No outgoing methods.
jfreerails.world.terrain.NullTerrainType.getProduction
Javadoc:
No Javadoc available
Method code:
public ImList<Production> getProduction() {
return new ImList<Production>();
}
No outgoing methods.
jfreerails.world.terrain.NullTerrainType.getRGB
Javadoc:
No Javadoc available
Method code:
public int getRGB() {
return 0;
}
No outgoing methods.
jfreerails.world.terrain.NullTerrainType.getRightOfWay
Javadoc:
No Javadoc available
Method code:
public int getRightOfWay() {
return 0;
}
No outgoing methods.
jfreerails.world.terrain.NullTerrainType.getTerrainTypeName
Javadoc:
No Javadoc available
Method code:
public String getTerrainTypeName() {
return "null";
}
No outgoing methods.
jfreerails.world.terrain.NullTerrainType.readResolve
Javadoc:
No Javadoc available
Method code:
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
No outgoing methods.
jfreerails.world.terrain.Production.getCargoType
Javadoc:
No Javadoc available
Method code:
public int getCargoType() {
return cargoType;
}
No outgoing methods.
jfreerails.world.terrain.Production.getRate
Javadoc:
No Javadoc available
Method code:
public int getRate() {
return rate;
}
No outgoing methods.
jfreerails.world.terrain.TerrainTile.getTerrainTypeID
Javadoc:
No Javadoc available
Method code:
int getTerrainTypeID();
No outgoing methods.
jfreerails.world.terrain.TerrainType.getBuildCost
Javadoc:
No Javadoc available
Method code:
Money getBuildCost();
No outgoing methods.
jfreerails.world.terrain.TerrainType.getCategory
Javadoc:
No Javadoc available
Method code:
Category getCategory();
No outgoing methods.
jfreerails.world.terrain.TerrainType.getConsumption
Javadoc:
No Javadoc available
Method code:
ImList<Consumption> getConsumption();
No outgoing methods.
jfreerails.world.terrain.TerrainType.getConversion
Javadoc:
No Javadoc available
Method code:
ImList<Conversion> getConversion();
No outgoing methods.
jfreerails.world.terrain.TerrainType.getDisplayName
Javadoc:
/** * Returns the display name of this terrain type, which is used for user interface purposes or identification. * * @return the human-readable name of the terrain type */
Method code:
String getDisplayName();
No outgoing methods.
jfreerails.world.terrain.TerrainType.getProduction
Javadoc:
No Javadoc available
Method code:
ImList<Production> getProduction();
No outgoing methods.
jfreerails.world.terrain.TerrainType.getRGB
Javadoc:
No Javadoc available
Method code:
int getRGB();
No outgoing methods.
jfreerails.world.terrain.TerrainType.getRightOfWay
Javadoc:
No Javadoc available
Method code:
int getRightOfWay();
No outgoing methods.
jfreerails.world.terrain.TerrainType.getTerrainTypeName
Javadoc:
No Javadoc available
Method code:
String getTerrainTypeName();
No outgoing methods.
jfreerails.world.terrain.TileTypeImpl.getBuildCost
Javadoc:
No Javadoc available
Method code:
public Money getBuildCost() {
return tileBuildCost;
}
No outgoing methods.
jfreerails.world.terrain.TileTypeImpl.getCategory
Javadoc:
No Javadoc available
Method code:
public Category getCategory() {
return terrainCategory;
}
No outgoing methods.
jfreerails.world.terrain.TileTypeImpl.getConsumption
Javadoc:
No Javadoc available
Method code:
public ImList<Consumption> getConsumption() {
return consumption;
}
No outgoing methods.
jfreerails.world.terrain.TileTypeImpl.getConversion
Javadoc:
No Javadoc available
Method code:
public ImList<Conversion> getConversion() {
return conversion;
}
No outgoing methods.
jfreerails.world.terrain.TileTypeImpl.getDisplayName
Javadoc:
/** Returns the name, replacing any underscores with spaces. */
Method code:
/** Returns the name, replacing any underscores with spaces. */
public String getDisplayName() {
return terrainType.replace('_', ' ');
}
No outgoing methods.
jfreerails.world.terrain.TileTypeImpl.getProduction
Javadoc:
No Javadoc available
Method code:
public ImList<Production> getProduction() {
return production;
}
No outgoing methods.
jfreerails.world.terrain.TileTypeImpl.getRGB
Javadoc:
/** * @return The RGB value mapped to this terrain type. */
Method code:
/**
* @return The RGB value mapped to this terrain type.
*/
public int getRGB() {
return rgb;
}
No outgoing methods.
jfreerails.world.terrain.TileTypeImpl.getRightOfWay
Javadoc:
No Javadoc available
Method code:
public int getRightOfWay() {
return rightOfWay;
}
No outgoing methods.
jfreerails.world.terrain.TileTypeImpl.getTerrainTypeName
Javadoc:
No Javadoc available
Method code:
public String getTerrainTypeName() {
return terrainType;
}
No outgoing methods.
jfreerails.world.top.ActivityIteratorImpl.absolute2relativeTime
Javadoc:
No Javadoc available
Method code:
public double absolute2relativeTime(double t) {
double dt = t - ant.startTime;
dt = Math.min(dt, ant.act.duration());
return dt;
}
Outgoing Methods (calls):
jfreerails.world.top.ActivityIteratorImpl.getActivity
Javadoc:
No Javadoc available
Method code:
public Activity getActivity() {
return ant.act;
}
No outgoing methods.
jfreerails.world.top.ActivityIteratorImpl.getDuration
Javadoc:
No Javadoc available
Method code:
public double getDuration() {
return ant.act.duration();
}
Outgoing Methods (calls):
jfreerails.world.top.ActivityIteratorImpl.getFinishTime
Javadoc:
No Javadoc available
Method code:
public double getFinishTime() {
double ticks = ant.startTime + ant.act.duration();
return ticks;
}
Outgoing Methods (calls):
jfreerails.world.top.ActivityIteratorImpl.getStartTime
Javadoc:
No Javadoc available
Method code:
public double getStartTime() {
return ant.startTime;
}
No outgoing methods.
jfreerails.world.top.ActivityIteratorImpl.getState
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable getState(double t) {
double dt = absolute2relativeTime(t);
return ant.act.getState(dt);
}
Outgoing Methods (calls):
jfreerails.world.top.ActivityIteratorImpl.gotoLastActivity
Javadoc:
No Javadoc available
Method code:
public void gotoLastActivity() {
activityIndex = size - 1;
ant = currentList.get(activityIndex);
}
No outgoing methods.
jfreerails.world.top.ActivityIteratorImpl.hasNext
Javadoc:
No Javadoc available
Method code:
public boolean hasNext() {
return (activityIndex + 1) < size;
}
No outgoing methods.
jfreerails.world.top.ActivityIteratorImpl.hasPrevious
Javadoc:
No Javadoc available
Method code:
public boolean hasPrevious() {
return activityIndex >= 1;
}
No outgoing methods.
jfreerails.world.top.ActivityIteratorImpl.nextActivity
Javadoc:
/** * Advances the iterator to the next activity in the sequence. * This method first checks if there is a next activity using {@link #hasNext()}. * If no next activity exists, a {@link NoSuchElementException} is thrown. * Otherwise, the internal activity index is incremented, and the next activity * is retrieved from the current list. * * @throws NoSuchElementException if there are no more activities to retrieve. */
Method code:
public void nextActivity() {
if (!hasNext()) {
throw new NoSuchElementException();
}
activityIndex++;
ant = currentList.get(activityIndex);
}
Outgoing Methods (calls):
jfreerails.world.top.ActivityIteratorImpl.previousActivity
Javadoc:
No Javadoc available
Method code:
public void previousActivity() throws NoSuchElementException {
if (!hasPrevious()) {
throw new NoSuchElementException();
}
activityIndex--;
ant = currentList.get(activityIndex);
}
Outgoing Methods (calls):
jfreerails.world.top.GameRules.isCanConnect2OtherRRTrack
Javadoc:
No Javadoc available
Method code:
public synchronized boolean isCanConnect2OtherRRTrack() {
return canConnect2OtherRRTrack;
}
No outgoing methods.
jfreerails.world.top.GameRules.isMustConnect2ExistingTrack
Javadoc:
No Javadoc available
Method code:
public synchronized boolean isMustConnect2ExistingTrack() {
return mustConnect2ExistingTrack;
}
No outgoing methods.
jfreerails.world.top.ITEM.getKeyID
Javadoc:
No Javadoc available
Method code:
int getKeyID() {
return keyNumber;
}
No outgoing methods.
jfreerails.world.top.ITEM.getNumberOfKeys
Javadoc:
No Javadoc available
Method code:
static int getNumberOfKeys() {
return ITEM.class.getFields().length;
}
No outgoing methods.
jfreerails.world.top.ITEM.readResolve
Javadoc:
No Javadoc available
Method code:
private Object readResolve() throws ObjectStreamException {
return keys[this.keyNumber];
}
No outgoing methods.
jfreerails.world.top.ItemsTransactionAggregator.calculateQuantitiesAndValues
Javadoc:
No Javadoc available
Method code:
public QuantitiesAndValues calculateQuantitiesAndValues() {
QuantitiesAndValues returnValue = new QuantitiesAndValues();
returnValue.values = super.calculateValues();
returnValue.quantities = this.quantities;
return returnValue;
}
Outgoing Methods (calls):
jfreerails.world.top.ItemsTransactionAggregator.calculateQuantity
Javadoc:
No Javadoc available
Method code:
public int calculateQuantity() {
QuantitiesAndValues qnv = calculateQuantitiesAndValues();
return qnv.quantities[0];
}
Outgoing Methods (calls):
jfreerails.world.top.ItemsTransactionAggregator.condition
Javadoc:
/** * Returns true if the transaction with the specified ID has an acceptable * type and category. */
Method code:
/**
* Returns true if the transaction with the specified ID has an acceptable
* type and category.
*/
@Override
protected boolean condition(int transactionID) {
Transaction t = w.getTransaction(principal, transactionID);
if (!(t instanceof AddItemTransaction)) {
return false;
}
AddItemTransaction addItemTransaction = (AddItemTransaction) t;
boolean isTypeAcceptable = (type == ANY_VALUE)
|| (type == addItemTransaction.getType());
boolean isCategoryAcceptable = (category == null)
|| (category == addItemTransaction.getCategory());
return isCategoryAcceptable && isTypeAcceptable;
}
Outgoing Methods (calls):
jfreerails.world.top.ItemsTransactionAggregator.getCategory
Javadoc:
No Javadoc available
Method code:
public Transaction.Category getCategory() {
return category;
}
No outgoing methods.
jfreerails.world.top.ItemsTransactionAggregator.getType
Javadoc:
No Javadoc available
Method code:
public int getType() {
return type;
}
No outgoing methods.
jfreerails.world.top.ItemsTransactionAggregator.incrementRunningTotal
Javadoc:
No Javadoc available
Method code:
@Override
protected void incrementRunningTotal(int transactionID) {
super.incrementRunningTotal(transactionID);
Transaction t = w.getTransaction(principal, transactionID);
AddItemTransaction addItemTransaction = (AddItemTransaction) t;
quantityRunningTotal += addItemTransaction.getQuantity();
}
Outgoing Methods (calls):
jfreerails.world.top.ItemsTransactionAggregator.setCategory
Javadoc:
No Javadoc available
Method code:
public void setCategory(Transaction.Category category) {
this.category = category;
}
No outgoing methods.
jfreerails.world.top.ItemsTransactionAggregator.setTotalsArrayLength
Javadoc:
No Javadoc available
Method code:
@Override
protected void setTotalsArrayLength(int length) {
super.setTotalsArrayLength(length);
quantities = new int[length];
quantityRunningTotal = 0;
}
Outgoing Methods (calls):
jfreerails.world.top.ItemsTransactionAggregator.setType
Javadoc:
No Javadoc available
Method code:
public void setType(int type) {
this.type = type;
}
No outgoing methods.
jfreerails.world.top.ItemsTransactionAggregator.storeRunningTotal
Javadoc:
No Javadoc available
Method code:
@Override
protected void storeRunningTotal(int timeIndex) {
/*
* Note, a negative sign since we are totalling the value of assets not
* their impact on the operating funds.
*/
monetaryTotals[timeIndex] = new Money(-runningTotal);
quantities[timeIndex] = quantityRunningTotal;
}
No outgoing methods.
jfreerails.world.top.ItemsTransactionAggregatorTest.test1
Javadoc:
No Javadoc available
Method code:
public void test1(){
World w = new WorldImpl();
Player player = new Player("name", 0);
w.addPlayer(player);
FreerailsPrincipal fp = w.getPlayer(0).getPrincipal();
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(w, fp);
aggregator.setCategory(TRACK);
int quant = aggregator.calculateQuantity();
assertEquals(0, quant);
Transaction t = new AddItemTransaction(Category.TRACK, 10, 5 , new Money(100));
w.addTransaction(fp, t);
quant = aggregator.calculateQuantity();
assertEquals(5, quant);
t = new AddItemTransaction(Category.TRACK, 10, 11 , new Money(200));
w.addTransaction(fp, t);
}
Outgoing Methods (calls):
jfreerails.world.top.KEY.getKey
Javadoc:
No Javadoc available
Method code:
public static KEY getKey(int keyNum) {
return keys[keyNum];
}
No outgoing methods.
jfreerails.world.top.KEY.getKeyID
Javadoc:
No Javadoc available
Method code:
int getKeyID() {
return keyNumber;
}
No outgoing methods.
jfreerails.world.top.KEY.getNumberOfKeys
Javadoc:
No Javadoc available
Method code:
static int getNumberOfKeys() {
return numberOfKeys;
}
No outgoing methods.
jfreerails.world.top.KEY.readResolve
Javadoc:
No Javadoc available
Method code:
private Object readResolve() throws ObjectStreamException {
return keys[this.keyNumber];
}
No outgoing methods.
jfreerails.world.top.KEYTest.testGetNumberOfKeys
Javadoc:
No Javadoc available
Method code:
public void testGetNumberOfKeys() {
// There were 4 keys when a wrote this test,
// but I expect the number to increase.
assertTrue(KEY.getNumberOfKeys() >= 4);
}
Outgoing Methods (calls):
jfreerails.world.top.KEYTest.testThatAllTheFieldsDefinedInKEYAreInstancesOFKEY
Javadoc:
No Javadoc available
Method code:
public void testThatAllTheFieldsDefinedInKEYAreInstancesOFKEY() {
Field[] fields = KEY.class.getFields();
for (int i = 0; i < fields.length; i++) {
String name = fields[i].getName();
int modifiers = fields[i].getModifiers();
if (!name.equals("shared")) {
assertTrue("All the fields of KEY should be static", Modifier
.isStatic(modifiers));
}
assertTrue("All the fields of KEY should be public", Modifier
.isPublic(modifiers));
assertTrue("All the fields of KEY should be final", Modifier
.isFinal(modifiers));
try {
if (Modifier.isStatic(modifiers)) {
Object o = fields[i].get(null);
assertTrue("All the fields of KEY should be instances of"
+ " KEY", o instanceof KEY);
}
} catch (IllegalAccessException e) {
assertTrue(false);
}
}
}
No outgoing methods.
jfreerails.world.top.KEYTest.testToString
Javadoc:
No Javadoc available
Method code:
public void testToString() {
assertEquals("Key.toString() should return the field name", "TRAINS",
KEY.TRAINS.toString());
}
Outgoing Methods (calls):
jfreerails.world.top.MapFixtureFactory.generateCargoTypesList
Javadoc:
/** Adds hard coded cargo types. */
Method code:
/** Adds hard coded cargo types. */
public static void generateCargoTypesList(World world) {
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Mail", Categories.Mail));
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Passengers",
Categories.Passengers));
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Goods",
Categories.Fast_Freight));
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Steel",
Categories.Slow_Freight));
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Coal",
Categories.Bulk_Freight));
}
Outgoing Methods (calls):
jfreerails.world.top.MapFixtureFactory.generateTerrainTypesList
Javadoc:
/** Adds hard coded terrain types. */
Method code:
/** Adds hard coded terrain types. */
private static void generateTerrainTypesList(World world) {
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Country, "Grassland"));
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Urban, "City"));
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Resource, "Mine"));
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Industry, "Factory"));
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Ocean, "Ocean"));
}
Outgoing Methods (calls):
jfreerails.world.top.MapFixtureFactory.generateTrackRuleList
Javadoc:
No Javadoc available
Method code:
public static void generateTrackRuleList(World world) {
TrackRule[] trackRulesArray = new TrackRule[3];
TrackRuleProperties[] trackRuleProperties = new TrackRuleProperties[3];
LegalTrackConfigurations[] legalTrackConfigurations = new LegalTrackConfigurations[3];
LegalTrackPlacement[] legalTrackPlacement = new LegalTrackPlacement[3];
HashSet<TerrainType.Category> cannotBuildOnTheseTerrainTypes = new HashSet<TerrainType.Category>();
cannotBuildOnTheseTerrainTypes.add(TerrainType.Category.Ocean);
// 1st track type..
String[] trackTemplates0 = { "000010000", "010010000", "010010010",
"100111000", "001111000", "010110000", "100110000", "100011000" };
legalTrackConfigurations[0] = new LegalTrackConfigurations(-1,
trackTemplates0);
trackRuleProperties[0] = new TrackRuleProperties(1, false, "type0",
TrackRule.TrackCategories.track, 0, 0, 10, 0);
legalTrackPlacement[0] = new LegalTrackPlacement(
cannotBuildOnTheseTerrainTypes,
LegalTrackPlacement.PlacementRule.ANYWHERE_EXCEPT_ON_THESE);
trackRulesArray[0] = new TrackRuleImpl(trackRuleProperties[0],
legalTrackConfigurations[0], legalTrackPlacement[0]);
// 2nd track type..
String[] trackTemplates1 = { "000010000", "010010000", "010010010" };
legalTrackConfigurations[1] = new LegalTrackConfigurations(-1,
trackTemplates1);
trackRuleProperties[1] = new TrackRuleProperties(2, false, "type1",
TrackRule.TrackCategories.track, 0, 0, 20, 0);
legalTrackPlacement[1] = new LegalTrackPlacement(
cannotBuildOnTheseTerrainTypes,
LegalTrackPlacement.PlacementRule.ANYWHERE_EXCEPT_ON_THESE);
trackRulesArray[1] = new TrackRuleImpl(trackRuleProperties[1],
legalTrackConfigurations[1], legalTrackPlacement[1]);
// 3rd track type..
trackRuleProperties[2] = new TrackRuleProperties(3, false, "type2",
TrackRule.TrackCategories.track, 0, 0, 30, 0);
String[] trackTemplates2 = { "000010000" };
legalTrackConfigurations[2] = new LegalTrackConfigurations(-1,
trackTemplates2);
legalTrackPlacement[2] = new LegalTrackPlacement(
cannotBuildOnTheseTerrainTypes,
LegalTrackPlacement.PlacementRule.ANYWHERE_EXCEPT_ON_THESE);
trackRulesArray[2] = new TrackRuleImpl(trackRuleProperties[2],
legalTrackConfigurations[2], legalTrackPlacement[2]);
// Add track rules to world
for (int i = 0; i < trackRulesArray.length; i++) {
world.add(SKEY.TRACK_RULES, trackRulesArray[i]);
}
// Add the terrain types if necessary.
if (world.size(SKEY.TERRAIN_TYPES) == 0) {
generateTerrainTypesList(world);
}
}
Outgoing Methods (calls):
jfreerails.world.top.MapFixtureFactory.getWorld
Javadoc:
/** * Returns a world object with a map of the specified size with the terrain * and cargo types setup. */
Method code:
/**
* Returns a world object with a map of the specified size with the terrain
* and cargo types setup.
*/
public static World getWorld(int w, int h) {
FreerailsTile tile = FreerailsTile.getInstance(0);
World world = new WorldImpl(w, h);
generateTerrainTypesList(world);
generateCargoTypesList(world);
for (int x = 0; x < w; x++) {
for (int y = 0; y < w; y++) {
world.setTile(x, y, tile);
}
}
return world;
}
Outgoing Methods (calls):
jfreerails.world.top.NonNullElements.getElement
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable getElement() {
return listGet(index);
}
Outgoing Methods (calls):
jfreerails.world.top.NonNullElements.getIndex
Javadoc:
No Javadoc available
Method code:
public int getIndex() {
return index;
}
No outgoing methods.
jfreerails.world.top.NonNullElements.getNaturalNumber
Javadoc:
No Javadoc available
Method code:
public int getNaturalNumber() {
return getRowID() + 1;
}
Outgoing Methods (calls):
jfreerails.world.top.NonNullElements.getRowID
Javadoc:
No Javadoc available
Method code:
public int getRowID() {
return row;
}
No outgoing methods.
jfreerails.world.top.NonNullElements.gotoIndex
Javadoc:
/** Moves the cursor to the specified index. */
Method code:
/** Moves the cursor to the specified index. */
public void gotoIndex(int i) {
int newRow = -1;
for (int j = 0; j < listSize(); j++) {
if (testCondition(j)) {
newRow++;
if (i == j) {
reset();
this.index = i;
this.row = newRow;
return;
}
}
}
throw new NoSuchElementException("Index:" + String.valueOf(i)
+ " Size:" + listSize() + " Row:" + newRow);
}
Outgoing Methods (calls):
jfreerails.world.top.NonNullElements.gotoRow
Javadoc:
/** * Moves the current row to the specified newRow by navigating through the sequence of elements. * If the current row is already equal to newRow, this method has no effect. * If newRow is greater than the current row, it advances to the target row using the {@code next()} method. * If newRow is less than the current row, it moves backward to the target row using the {@code previous()} method. * * @param newRow the target row index to move to */
Method code:
public void gotoRow(int newRow) {
if (row == newRow) {
return;
}
if (row < newRow) {
while (row != newRow) {
next();
}
} else {
while (row != newRow) {
previous();
}
}
return;
}
Outgoing Methods (calls):
jfreerails.world.top.NonNullElements.listGet
Javadoc:
No Javadoc available
Method code:
private FreerailsSerializable listGet(int i) {
if (null == this.skey) {
return w.get(principal, key, i);
}
return w.get(skey, i);
}
Outgoing Methods (calls):
jfreerails.world.top.NonNullElements.listSize
Javadoc:
No Javadoc available
Method code:
private int listSize() {
if (null == this.skey) {
return w.size(principal, key);
}
return w.size(this.skey);
}
Outgoing Methods (calls):
jfreerails.world.top.NonNullElements.next
Javadoc:
No Javadoc available
Method code:
public boolean next() {
int nextIndex = index; // this is used to look ahead.
do {
nextIndex++;
if (nextIndex >= listSize()) {
return false;
}
} while (!testCondition(nextIndex));
row++;
index = nextIndex;
return true;
}
Outgoing Methods (calls):
jfreerails.world.top.NonNullElements.previous
Javadoc:
No Javadoc available
Method code:
public boolean previous() {
int previousIndex = index; // this is used to look back.
do {
previousIndex--;
if (previousIndex < 0) {
return false;
}
} while (!testCondition(previousIndex));
row--;
index = previousIndex;
return true;
}
Outgoing Methods (calls):
jfreerails.world.top.NonNullElements.reset
Javadoc:
No Javadoc available
Method code:
public void reset() {
index = -1;
row = -1;
size = -1;
}
No outgoing methods.
jfreerails.world.top.NonNullElements.row2index
Javadoc:
No Javadoc available
Method code:
public static int row2index(ReadOnlyWorld w, KEY key, FreerailsPrincipal p,
int row) {
int count = 0;
for (int i = 0; i < w.size(p, key); i++) {
if (w.get(p, key, i) != null) {
if (count == row) {
return i;
}
count++;
}
}
throw new NoSuchElementException(String.valueOf(row));
}
Outgoing Methods (calls):
jfreerails.world.top.NonNullElements.size
Javadoc:
No Javadoc available
Method code:
public int size() {
if (-1 == size) { // lazy loading, if we have already calculated the
// size don't do it again.
int tempSize = 0;
for (int i = 0; i < listSize(); i++) {
if (null != listGet(i)) {
tempSize++;
}
}
size = tempSize;
}
return size;
}
Outgoing Methods (calls):
jfreerails.world.top.NonNullElements.testCondition
Javadoc:
No Javadoc available
Method code:
protected boolean testCondition(int i) {
return null != listGet(i);
}
Outgoing Methods (calls):
jfreerails.world.top.NonNullElementsTest.main
Javadoc:
No Javadoc available
Method code:
public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}
Outgoing Methods (calls):
jfreerails.world.top.NonNullElementsTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() {
w = new WorldImpl();
station1 = new StationModel(10, 20, "Station1", 4, 0);
station2 = new StationModel(15, 16, "Station2", 4, 1);
station3 = new StationModel(30, 50, "Station3", 4, 2);
w.addPlayer(MapFixtureFactory.TEST_PLAYER);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, station1);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, null);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, station2);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, null);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, null);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, station3);
}
Outgoing Methods (calls):
jfreerails.world.top.NonNullElementsTest.suite
Javadoc:
No Javadoc available
Method code:
public static Test suite() {
TestSuite testSuite = new TestSuite(NonNullElementsTest.class);
return testSuite;
}
No outgoing methods.
jfreerails.world.top.NonNullElementsTest.testGotoIndex
Javadoc:
/** * Tests the {@link WorldIterator#gotoIndex(int)} method to ensure it correctly * navigates to the specified index, updates the row ID, and throws * {@link NoSuchElementException} for invalid indices. */
Method code:
public void testGotoIndex() {
WorldIterator wi = new NonNullElements(KEY.STATIONS, w,
MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(WorldIterator.BEFORE_FIRST, wi.getRowID());
assertEquals(WorldIterator.BEFORE_FIRST, wi.getIndex());
wi.gotoIndex(2);
assertEquals(2, wi.getIndex());
assertEquals(1, wi.getRowID());
try {
wi.gotoIndex(100);
assertTrue(false);
} catch (NoSuchElementException e) {
}
}
Outgoing Methods (calls):
jfreerails.world.top.NonNullElementsTest.testNext
Javadoc:
No Javadoc available
Method code:
public void testNext() {
WorldIterator wi = new NonNullElements(KEY.STATIONS, w,
MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(WorldIterator.BEFORE_FIRST, wi.getRowID());
assertEquals(WorldIterator.BEFORE_FIRST, wi.getIndex());
// Look at first station
boolean b = wi.next();
assertTrue(b);
int index = wi.getIndex();
assertEquals(0, index);
assertEquals(0, wi.getRowID());
assertEquals(station1, wi.getElement());
// Look at second station
assertTrue(wi.next());
assertEquals(2, wi.getIndex());
assertEquals(1, wi.getRowID());
assertEquals(station2, wi.getElement());
WorldIterator wi2 = new NonNullElements(SKEY.TRACK_RULES, w);
assertTrue(!wi2.next());
}
Outgoing Methods (calls):
jfreerails.world.top.ReadOnlyWorld.boundsContain
Javadoc:
No Javadoc available
Method code:
boolean boundsContain(SKEY k, int index);
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.currentTime
Javadoc:
No Javadoc available
Method code:
GameTime currentTime();
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.get
Javadoc:
/** * Returns the element at the specified position in the specified list. */
Method code:
/**
* Returns the element at the specified position in the specified list.
*/
FreerailsSerializable get(SKEY key, int index);
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.getActivities
Javadoc:
No Javadoc available
Method code:
ActivityIterator getActivities(FreerailsPrincipal p, int index);
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.getCurrentBalance
Javadoc:
No Javadoc available
Method code:
Money getCurrentBalance(FreerailsPrincipal p);
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.getID
Javadoc:
No Javadoc available
Method code:
int getID(FreerailsPrincipal p);
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.getMapHeight
Javadoc:
/** * Returns the height of the map in tiles. */
Method code:
/**
* Returns the height of the map in tiles.
*/
int getMapHeight();
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.getMapWidth
Javadoc:
/** * Returns the width of the map in tiles. */
Method code:
/**
* Returns the width of the map in tiles.
*/
int getMapWidth();
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.getNumberOfActiveEntities
Javadoc:
No Javadoc available
Method code:
int getNumberOfActiveEntities(FreerailsPrincipal p);
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.getNumberOfPlayers
Javadoc:
No Javadoc available
Method code:
int getNumberOfPlayers();
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.getNumberOfTransactions
Javadoc:
No Javadoc available
Method code:
int getNumberOfTransactions(FreerailsPrincipal p);
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.getPlayer
Javadoc:
No Javadoc available
Method code:
Player getPlayer(int i);
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.getTile
Javadoc:
/** * Returns the tile at the specified position on the map. */
Method code:
/**
* Returns the tile at the specified position on the map.
*/
FreerailsSerializable getTile(int x, int y);
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.getTransaction
Javadoc:
No Javadoc available
Method code:
Transaction getTransaction(FreerailsPrincipal p, int i);
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.getTransactionAndTimeStamp
Javadoc:
/** * Retrieves the transaction and game time associated with the specified principal and index. * * @param p the FreerailsPrincipal representing the user or entity making the transaction * @param i the index or identifier used to locate the specific transaction * @return a Pair containing the transaction and the corresponding game time */
Method code:
public Pair<Transaction, GameTime> getTransactionAndTimeStamp(
FreerailsPrincipal p, int i);
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.getTransactionTimeStamp
Javadoc:
No Javadoc available
Method code:
GameTime getTransactionTimeStamp(FreerailsPrincipal p, int i);
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.isPlayer
Javadoc:
No Javadoc available
Method code:
boolean isPlayer(FreerailsPrincipal p);
No outgoing methods.
jfreerails.world.top.ReadOnlyWorld.size
Javadoc:
/** * Returns number of active entities belonging to the specified principal. */
Method code:
/**
* Returns number of active entities belonging to the specified principal.
*/
int size(FreerailsPrincipal p);
No outgoing methods.
jfreerails.world.top.SKEY.getKey
Javadoc:
No Javadoc available
Method code:
static SKEY getKey(int keyNum) {
return keys[keyNum];
}
No outgoing methods.
jfreerails.world.top.SKEY.getKeyID
Javadoc:
No Javadoc available
Method code:
int getKeyID() {
return keyNumber;
}
No outgoing methods.
jfreerails.world.top.SKEY.getNumberOfKeys
Javadoc:
/** * Returns the number of keys (fields) defined in the SKEY class. * This value is determined by counting the number of fields exposed by the SKEY class. * * @return the number of keys (fields) in the SKEY class */
Method code:
static int getNumberOfKeys() {
return SKEY.class.getFields().length;
}
No outgoing methods.
jfreerails.world.top.SKEY.readResolve
Javadoc:
No Javadoc available
Method code:
private Object readResolve() throws ObjectStreamException {
return keys[this.keyNumber];
}
No outgoing methods.
jfreerails.world.top.SKEYTest.testGetNumberOfKeys
Javadoc:
No Javadoc available
Method code:
public void testGetNumberOfKeys() {
assertTrue(SKEY.getNumberOfKeys() > 5);
}
Outgoing Methods (calls):
jfreerails.world.top.SKEYTest.testThatAllTheFieldsDefinedInSKEYAreInstancesOFSKEY
Javadoc:
No Javadoc available
Method code:
public void testThatAllTheFieldsDefinedInSKEYAreInstancesOFSKEY() {
Field[] fields = SKEY.class.getFields();
for (int i = 0; i < fields.length; i++) {
String name = fields[i].getName();
int modifiers = fields[i].getModifiers();
if (!name.equals("shared")) {
assertTrue("All the fields of SKEY should be static", Modifier
.isStatic(modifiers));
}
assertTrue("All the fields of SKEY should be public", Modifier
.isPublic(modifiers));
assertTrue("All the fields of SKEY should be final", Modifier
.isFinal(modifiers));
try {
if (Modifier.isStatic(modifiers)) {
Object o = fields[i].get(null);
assertTrue("All the fields of SKEY should be instances of"
+ " SKEY", o instanceof SKEY);
}
} catch (IllegalAccessException e) {
assertTrue(false);
}
}
}
No outgoing methods.
jfreerails.world.top.TestActivity.duration
Javadoc:
/** * Returns the duration value stored in this object. * * @return the duration in seconds */
Method code:
public double duration() {
return duration;
}
No outgoing methods.
jfreerails.world.top.TestActivity.getState
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable getState(double dt) {
return new TestState((int) dt);
}
No outgoing methods.
jfreerails.world.top.TransactionAggregator.calculateValue
Javadoc:
/** Returns the sum of the appropriate transactions. Do not override. */
Method code:
/** Returns the sum of the appropriate transactions. Do not override. */
final public Money calculateValue() {
Money[] values = calculateValues();
return values[0];
}
Outgoing Methods (calls):
jfreerails.world.top.TransactionAggregator.calculateValues
Javadoc:
/** * Returns the sum of the appropriate transactions up to (inclusive) each of * the specified times. Do not override. */
Method code:
/**
* Returns the sum of the appropriate transactions up to (inclusive) each of
* the specified times. Do not override.
*/
final public Money[] calculateValues() {
setTotalsArrayLength(timeValues.length - 1);
int timeIndex = 0;
int numberOfTransactions = w.getNumberOfTransactions(this.principal);
setTotalsArrayLength(timeValues.length - 1);
for (int i = 0; i < numberOfTransactions; i++) {
GameTime time = w.getTransactionTimeStamp(principal, i);
int transactionTime = time.getTicks();
while (timeValues[timeIndex].getTicks() <= transactionTime) {
storeTotalIfAppropriate(timeIndex);
timeIndex++;
if (timeIndex >= timeValues.length) {
/*
* The current transaction occurred after the last of the
* specified times.
*/
return monetaryTotals;
}
}
if (timeIndex > 0 && condition(i)) {
incrementRunningTotal(i);
}
}
/*
* There are no more transactions and the last transaction occurred
* before one or more of the specified times.
*/
while (timeIndex < timeValues.length) {
storeTotalIfAppropriate(timeIndex);
timeIndex++;
}
return monetaryTotals;
}
Outgoing Methods (calls):
jfreerails.world.top.TransactionAggregator.condition
Javadoc:
/** Returns true if we should count the specified transactions. */
Method code:
/** Returns true if we should count the specified transactions. */
abstract protected boolean condition(int transactionID);
No outgoing methods.
jfreerails.world.top.TransactionAggregator.getTimes
Javadoc:
No Javadoc available
Method code:
public GameTime[] getTimes() {
// return defensive copy.
return timeValues.clone();
}
Outgoing Methods (calls):
jfreerails.world.top.TransactionAggregator.incrementRunningTotal
Javadoc:
No Javadoc available
Method code:
protected void incrementRunningTotal(int transactionID) {
Transaction t = w.getTransaction(principal, transactionID);
runningTotal += t.deltaCash().getAmount();
}
Outgoing Methods (calls):
jfreerails.world.top.TransactionAggregator.setTimes
Javadoc:
No Javadoc available
Method code:
public void setTimes(GameTime[] times) {
if (1 > times.length) {
throw new IllegalArgumentException(
"There must be at least two values.");
}
timeValues = new GameTime[times.length];
timeValues[0] = times[0]; // since we start counting at 1.
for (int i = 1; i < times.length; i++) {
if (times[i].getTicks() < times[i - 1].getTicks()) {
throw new IllegalArgumentException("Time at index " + (i - 1)
+ " > time at index " + i + ".");
}
timeValues[i] = times[i];
}
}
Outgoing Methods (calls):
jfreerails.world.top.TransactionAggregator.setTotalsArrayLength
Javadoc:
/** * Creates a new array with the specified length to store monetary totals * and sets the running total to zero. Subclasses that aggregate other * quantities should override this method and create the appropriate arrays. */
Method code:
/**
* Creates a new array with the specified length to store monetary totals
* and sets the running total to zero. Subclasses that aggregate other
* quantities should override this method and create the appropriate arrays.
*/
protected void setTotalsArrayLength(int length) {
monetaryTotals = new Money[length];
runningTotal = 0;
}
No outgoing methods.
jfreerails.world.top.TransactionAggregator.storeRunningTotal
Javadoc:
/** * Stores the current running total in the totals array at the specified * position. */
Method code:
/**
* Stores the current running total in the totals array at the specified
* position.
*/
protected void storeRunningTotal(int timeIndex) {
monetaryTotals[timeIndex] = new Money(runningTotal);
}
No outgoing methods.
jfreerails.world.top.TransactionAggregator.storeTotalIfAppropriate
Javadoc:
No Javadoc available
Method code:
private void storeTotalIfAppropriate(int timeIndex) {
if (timeIndex > 0) {
storeRunningTotal(timeIndex - 1);
}
}
Outgoing Methods (calls):
jfreerails.world.top.TypeID.getID
Javadoc:
No Javadoc available
Method code:
public int getID() {
return id;
}
No outgoing methods.
jfreerails.world.top.TypeID.getKey
Javadoc:
No Javadoc available
Method code:
public SKEY getKey() {
return key;
}
No outgoing methods.
jfreerails.world.top.WagonAndEngineTypesFactory.addTypesToWorld
Javadoc:
No Javadoc available
Method code:
public void addTypesToWorld(World w) {
// Wagon types
WagonType[] wagonTypes = new WagonType[] {
new WagonType("Mail", WagonType.MAIL),
new WagonType("Passengers", WagonType.PASSENGER),
new WagonType("Livestock", WagonType.FAST_FREIGHT),
new WagonType("Coffee", WagonType.SLOW_FREIGHT),
new WagonType("Wood", WagonType.BULK_FREIGHT), };
for (int i = 0; i < wagonTypes.length; i++) {
w.add(SKEY.WAGON_TYPES, wagonTypes[i]);
}
// Engine types
EngineType[] engineTypes = new EngineType[] {
new EngineType("Grasshopper", 1000, new Money(10000), 10,
new Money(100)),
new EngineType("Norris", 1000, new Money(10000), 15, new Money(
100)), };
for (int i = 0; i < engineTypes.length; i++) {
w.add(SKEY.ENGINE_TYPES, engineTypes[i]);
}
}
Outgoing Methods (calls):
jfreerails.world.top.World.add
Javadoc:
/** * Appends the specified element to the end of the specified list and returns * the index that can be used to retrieve it. * */
Method code:
/**
* Appends the specified element to the end of the specified list and returns
* the index that can be used to retrieve it.
*
*/
int add(SKEY key, FreerailsSerializable element);
No outgoing methods.
jfreerails.world.top.World.addActiveEntity
Javadoc:
No Javadoc available
Method code:
int addActiveEntity(FreerailsPrincipal principal, Activity element);
No outgoing methods.
jfreerails.world.top.World.addPlayer
Javadoc:
No Javadoc available
Method code:
int addPlayer(Player player);
No outgoing methods.
jfreerails.world.top.World.addTransaction
Javadoc:
/** * Adds the specified transaction to the specified principal's bank account. */
Method code:
/**
* Adds the specified transaction to the specified principal's bank account.
*/
void addTransaction(FreerailsPrincipal p, Transaction t);
No outgoing methods.
jfreerails.world.top.World.defensiveCopy
Javadoc:
/** * Returns a copy of this world object - making changes to this copy will * not change this object. */
Method code:
/**
* Returns a copy of this world object - making changes to this copy will
* not change this object.
*/
World defensiveCopy();
No outgoing methods.
jfreerails.world.top.World.removeLast
Javadoc:
/** * Removes the last element from the specified list. */
Method code:
/**
* Removes the last element from the specified list.
*/
FreerailsSerializable removeLast(FreerailsPrincipal principal, KEY key);
No outgoing methods.
jfreerails.world.top.World.removeLastActiveEntity
Javadoc:
No Javadoc available
Method code:
Activity removeLastActiveEntity(FreerailsPrincipal principal);
No outgoing methods.
jfreerails.world.top.World.removeLastActivity
Javadoc:
/** * Removes the activity at the specified index from the list of activities * associated with the given principal and returns the removed activity. * * @param principal the FreerailsPrincipal representing the user performing the action * @param index the index of the activity to remove * @return the Activity that was removed */
Method code:
Activity removeLastActivity(FreerailsPrincipal principal, int index);
No outgoing methods.
jfreerails.world.top.World.removeLastPlayer
Javadoc:
No Javadoc available
Method code:
Player removeLastPlayer();
No outgoing methods.
jfreerails.world.top.World.removeLastTransaction
Javadoc:
/** * Removes and returns the last transaction added the the specified * principal's bank account. This method is only here so that moves that add * transactions can be undone. */
Method code:
/**
* Removes and returns the last transaction added the the specified
* principal's bank account. This method is only here so that moves that add
* transactions can be undone.
*/
Transaction removeLastTransaction(FreerailsPrincipal p);
No outgoing methods.
jfreerails.world.top.World.set
Javadoc:
/** * Replaces the element mapped to the specified item with the specified * element. * */
Method code:
/**
* Replaces the element mapped to the specified item with the specified
* element.
*
*/
void set(ITEM item, FreerailsSerializable element);
No outgoing methods.
jfreerails.world.top.World.setTile
Javadoc:
/** * Replaces the tile at the specified position on the map with the specified * tile. * */
Method code:
/**
* Replaces the tile at the specified position on the map with the specified
* tile.
*
*/
void setTile(int x, int y, FreerailsSerializable tile);
No outgoing methods.
jfreerails.world.top.World.setTime
Javadoc:
No Javadoc available
Method code:
void setTime(GameTime t);
No outgoing methods.
jfreerails.world.top.WorldDiffs.getDiff
Javadoc:
No Javadoc available
Method code:
public Object getDiff(ListKey key){
return listDiff.get(key);
}
No outgoing methods.
jfreerails.world.top.WorldDiffs.getListDiffs
Javadoc:
No Javadoc available
Method code:
public Iterator<ListKey> getListDiffs() {
return listDiff.keySet().iterator();
}
No outgoing methods.
jfreerails.world.top.WorldDiffs.getMapDiffs
Javadoc:
/** * The iterator returns instances of java.awt.Point that store the * coordinates of tiles that are different to the underlying world object. */
Method code:
/**
* The iterator returns instances of java.awt.Point that store the
* coordinates of tiles that are different to the underlying world object.
*/
public Iterator<ImPoint> getMapDiffs() {
return mapDiff.keySet().iterator();
}
No outgoing methods.
jfreerails.world.top.WorldDiffs.getMapHeight
Javadoc:
No Javadoc available
Method code:
@Override
public int getMapHeight() {
return underlying.getMapHeight();
}
Outgoing Methods (calls):
jfreerails.world.top.WorldDiffs.getMapWidth
Javadoc:
No Javadoc available
Method code:
@Override
public int getMapWidth() {
return underlying.getMapWidth();
}
Outgoing Methods (calls):
jfreerails.world.top.WorldDiffs.getTile
Javadoc:
No Javadoc available
Method code:
@Override
public FreerailsSerializable getTile(int x, int y) {
ImPoint p = new ImPoint(x, y);
if (this.mapDiff.containsKey(p)) {
return (FreerailsSerializable) this.mapDiff.get(p);
}
return underlying.getTile(x, y);
}
Outgoing Methods (calls):
jfreerails.world.top.WorldDiffs.getUnderlying
Javadoc:
No Javadoc available
Method code:
public ReadOnlyWorld getUnderlying() {
return underlying;
}
No outgoing methods.
jfreerails.world.top.WorldDiffs.isDifferent
Javadoc:
No Javadoc available
Method code:
public boolean isDifferent(){
return (mapDiff.size() != 0) || (listDiff.size() != 0);
}
No outgoing methods.
jfreerails.world.top.WorldDiffs.listDiffs
Javadoc:
/** Used by unit tests. */
Method code:
/** Used by unit tests. */
public int listDiffs() {
return listDiff.size();
}
No outgoing methods.
jfreerails.world.top.WorldDiffs.numberOfMapDifferences
Javadoc:
/** Used by unit tests. */
Method code:
/** Used by unit tests. */
public int numberOfMapDifferences() {
return this.mapDiff.size();
}
No outgoing methods.
jfreerails.world.top.WorldDiffs.reset
Javadoc:
/** * After this method returns, all differences are cleared and calls to * methods on this object should produce the same results as calls the the * corresponding methods on the underlying world object. */
Method code:
/**
* After this method returns, all differences are cleared and calls to
* methods on this object should produce the same results as calls the the
* corresponding methods on the underlying world object.
*/
public void reset() {
time = underlying.currentTime();
mapDiff.clear();
listDiff.clear();
}
Outgoing Methods (calls):
jfreerails.world.top.WorldDiffs.setTile
Javadoc:
No Javadoc available
Method code:
@Override
public void setTile(int x, int y, FreerailsSerializable tile) {
ImPoint p = new ImPoint(x, y);
if (Utils.equal(underlying.getTile(x, y), tile)) {
if (this.mapDiff.containsKey(p)) {
this.mapDiff.remove(p);
return;
}
} else {
this.mapDiff.put(p, tile);
}
}
Outgoing Methods (calls):
jfreerails.world.top.WorldDiffsTest.testAccount
Javadoc:
No Javadoc available
Method code:
public void testAccount(){
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(0, worldDiff.numberOfMapDifferences());
assertEquals(0, worldDiff.listDiffs());
}
Outgoing Methods (calls):
jfreerails.world.top.WorldDiffsTest.testEquals
Javadoc:
No Javadoc available
Method code:
public void testEquals(){
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
WorldDiffs a = new WorldDiffs(underlyingWorld);
WorldDiffs b = new WorldDiffs(underlyingWorld);
assertEquals(a, a);
assertEquals(a, b);
assertEquals(a, underlyingWorld);
assertEquals(underlyingWorld, a);
}
Outgoing Methods (calls):
jfreerails.world.top.WorldDiffsTest.testGetListDiffs
Javadoc:
No Javadoc available
Method code:
public void testGetListDiffs(){
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
WorldDiffs diffs = new WorldDiffs(underlyingWorld);
CityModel city = new CityModel("Bristol", 10, 4);
diffs.add(SKEY.CITIES, city);
Iterator<ListKey> it = diffs.getListDiffs();
@SuppressWarnings("unused")
ListKey lk1 = it.next();
ListKey lk2 = it.next();
assertFalse(it.hasNext());
ListKey expected = new ListKey(Element, SHARED_LISTS, SKEY.CITIES.getKeyID(), 0);
assertEquals(expected, lk2);
}
Outgoing Methods (calls):
jfreerails.world.top.WorldDiffsTest.testItem
Javadoc:
No Javadoc available
Method code:
public void testItem() {
WorldImpl underlyingWorld = new WorldImpl(10, 10);
StationModel station0 = new StationModel();
StationModel station1 = new StationModel();
underlyingWorld.set(ITEM.GAME_RULES, station0); // why not!
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(station0, worldDiff.get(ITEM.GAME_RULES));
worldDiff.set(ITEM.GAME_RULES, station1);
assertEquals(station1, worldDiff.get(ITEM.GAME_RULES));
}
Outgoing Methods (calls):
jfreerails.world.top.WorldDiffsTest.testMap
Javadoc:
No Javadoc available
Method code:
public void testMap() {
WorldImpl underlyingWorld = new WorldImpl(21, 8);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(21, worldDiff.getMapWidth());
assertEquals(8, worldDiff.getMapHeight());
FreerailsTile tile = (FreerailsTile) underlyingWorld.getTile(2, 2);
assertNotNull(tile);
assertEquals(tile, worldDiff.getTile(2, 2));
FreerailsTile newTile = FreerailsTile.getInstance(999);
worldDiff.setTile(3, 5, newTile);
assertEquals(newTile, worldDiff.getTile(3, 5));
Iterator<ImPoint> it = worldDiff.getMapDiffs();
assertEquals(new ImPoint(3, 5), it.next());
}
Outgoing Methods (calls):
jfreerails.world.top.WorldDiffsTest.testNonSharedLists
Javadoc:
No Javadoc available
Method code:
public void testNonSharedLists() {
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
StationModel station0 = new StationModel();
underlyingWorld.add(player0.getPrincipal(), KEY.STATIONS, station0);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(0, worldDiff.listDiffs());
// First, for an existing player
assertEquals(1, worldDiff.size(player0.getPrincipal(), KEY.STATIONS));
FreerailsSerializable fs = worldDiff.get(player0.getPrincipal(),
KEY.STATIONS, 0);
assertEquals(station0, fs);
// Add a station.
StationModel station1 = new StationModel();
worldDiff.add(player0.getPrincipal(), KEY.STATIONS, station1);
assertEquals(2, worldDiff.size(player0.getPrincipal(), KEY.STATIONS));
fs = worldDiff.get(player0.getPrincipal(), KEY.STATIONS, 1);
assertEquals(station1, fs);
// Change a station.
StationModel station2 = new StationModel();
worldDiff.set(player0.getPrincipal(), KEY.STATIONS, 0, station2);
fs = worldDiff.get(player0.getPrincipal(), KEY.STATIONS, 0);
assertEquals(station2, fs);
// Remove both stations.
fs = worldDiff.removeLast(player0.getPrincipal(), KEY.STATIONS);
assertEquals(station1, fs);
fs = worldDiff.removeLast(player0.getPrincipal(), KEY.STATIONS);
assertEquals(station2, fs);
assertEquals(0, worldDiff.size(player0.getPrincipal(), KEY.STATIONS));
// Add a station again.
int i = worldDiff.add(player0.getPrincipal(), KEY.STATIONS, station1);
assertEquals(0, i);
assertEquals(1, worldDiff.size(player0.getPrincipal(), KEY.STATIONS));
// Second, for a new player
worldDiff.addPlayer(player1);
assertEquals(2, worldDiff.getNumberOfPlayers());
assertEquals(player1, worldDiff.getPlayer(1));
assertEquals(0, worldDiff.size(player1.getPrincipal(), KEY.STATIONS));
worldDiff.add(player1.getPrincipal(), KEY.STATIONS, station1);
assertEquals(1, worldDiff.size(player1.getPrincipal(), KEY.STATIONS));
worldDiff.set(player1.getPrincipal(), KEY.STATIONS, 0, station2);
worldDiff.add(player1.getPrincipal(), KEY.STATIONS, station1);
}
Outgoing Methods (calls):
jfreerails.world.top.WorldDiffsTest.testPlayers
Javadoc:
No Javadoc available
Method code:
public void testPlayers() {
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(0, worldDiff.listDiffs());
assertEquals(1, worldDiff.getNumberOfPlayers());
Player p = worldDiff.getPlayer(0);
assertEquals(player0, p);
assertTrue(worldDiff.isPlayer(player0.getPrincipal()));
// Test adding a player.
int n = worldDiff.addPlayer(player1);
assertEquals(1, n);
assertEquals(2, worldDiff.getNumberOfPlayers());
p = worldDiff.getPlayer(1);
assertEquals(player1, p);
assertTrue(worldDiff.isPlayer(player1.getPrincipal()));
}
Outgoing Methods (calls):
jfreerails.world.top.WorldDiffsTest.testSharedLists
Javadoc:
No Javadoc available
Method code:
public void testSharedLists() {
WorldImpl underlyingWorld = new WorldImpl(10, 10);
CargoType mailCT = new CargoType(10, "Mail", Categories.Mail);
CargoType passengersCT = new CargoType(10, "Passengers",
Categories.Passengers);
underlyingWorld.add(SKEY.CARGO_TYPES, mailCT);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(0, worldDiff.listDiffs());
assertEquals(1, worldDiff.size(SKEY.CARGO_TYPES));
FreerailsSerializable f = worldDiff.get(SKEY.CARGO_TYPES, 0);
assertEquals("The mail cargotype should be accessible.", mailCT, f);
worldDiff.add(SKEY.CARGO_TYPES, passengersCT);
assertEquals(2, worldDiff.size(SKEY.CARGO_TYPES));
assertEquals("2 Diffs: the length of the list + the actual element", 2,
worldDiff.listDiffs());
f = worldDiff.removeLast(SKEY.CARGO_TYPES);
assertEquals(passengersCT, f);
assertEquals(0, worldDiff.listDiffs());
f = worldDiff.removeLast(SKEY.CARGO_TYPES);
assertEquals(mailCT, f);
assertEquals("1 Diff: the list length.", 1, worldDiff.listDiffs());
assertEquals(0 , worldDiff.size(SKEY.CARGO_TYPES));
worldDiff.add(SKEY.CARGO_TYPES, mailCT);
assertEquals(0, worldDiff.listDiffs());
worldDiff.set(SKEY.CARGO_TYPES, 0, passengersCT);
assertEquals("1 Diff: element 0", 1, worldDiff.listDiffs());
}
Outgoing Methods (calls):
jfreerails.world.top.WorldDiffsTest.testUsingNullElements
Javadoc:
No Javadoc available
Method code:
public void testUsingNullElements() {
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
StationModel station0 = new StationModel();
StationModel station1 = null;
underlyingWorld.add(player0.getPrincipal(), KEY.STATIONS, station0);
underlyingWorld.add(player0.getPrincipal(), KEY.STATIONS, station1);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(station0, worldDiff.get(player0
.getPrincipal(), KEY.STATIONS, 0));
assertEquals(station1, worldDiff.get(player0
.getPrincipal(), KEY.STATIONS, 1));
worldDiff.set(player0.getPrincipal(), KEY.STATIONS, 0, station1);
worldDiff.set(player0.getPrincipal(), KEY.STATIONS, 1, station0);
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.add
Javadoc:
No Javadoc available
Method code:
public int add(SKEY key, FreerailsSerializable element) {
return sharedLists.addD2(key.getKeyID(), element);
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.addActiveEntity
Javadoc:
No Javadoc available
Method code:
public int addActiveEntity(FreerailsPrincipal p, Activity element) {
int playerIndex = p.getWorldIndex();
int index = activityLists.addD2(playerIndex);
ActivityAndTime ant = new ActivityAndTime(element, currentTime()
.getTicks());
activityLists.addD3(playerIndex, index, ant);
return index;
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.addPlayer
Javadoc:
/** * @param player * Player to add * @return index of the player */
Method code:
/**
* @param player
* Player to add
* @return index of the player
*/
public int addPlayer(Player player) {
if (null == player) {
throw new NullPointerException();
}
int index = players.add(player);
bankAccounts.addD1();
currentBalance.add(new Money(0));
lists.addD1();
for (int i = 0; i < KEY.getNumberOfKeys(); i++) {
lists.addD2(index);
}
activityLists.addD1();
return index;
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.addTransaction
Javadoc:
No Javadoc available
Method code:
public void addTransaction(FreerailsPrincipal p, Transaction t) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = new TransactionAndTimeStamp(t, time);
bankAccounts.addD2(playerIndex, tats);
Money oldBalance = currentBalance.get(playerIndex);
Money newBalance = new Money(t.deltaCash().getAmount()
+ oldBalance.getAmount());
currentBalance.set(playerIndex, newBalance);
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.boundsContain
Javadoc:
No Javadoc available
Method code:
public boolean boundsContain(int x, int y) {
if (x >= 0 && x < getMapWidth() && y >= 0 && y < getMapHeight()) {
return true;
}
return false;
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.currentTime
Javadoc:
No Javadoc available
Method code:
public GameTime currentTime() {
return time;
}
No outgoing methods.
jfreerails.world.top.WorldImpl.defensiveCopy
Javadoc:
No Javadoc available
Method code:
public World defensiveCopy() {
return (World) Utils.cloneBySerialisation(this);
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.get
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable get(ITEM item) {
return items.get(item.getKeyID());
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.getActivities
Javadoc:
No Javadoc available
Method code:
public ActivityIterator getActivities(final FreerailsPrincipal p, int index) {
final int playerIndex = p.getWorldIndex();
return new ActivityIteratorImpl(playerIndex, index);
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.getCurrentBalance
Javadoc:
No Javadoc available
Method code:
public Money getCurrentBalance(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
return currentBalance.get(playerIndex);
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.getID
Javadoc:
No Javadoc available
Method code:
public int getID(FreerailsPrincipal p) {
return p.getWorldIndex();
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.getMapHeight
Javadoc:
No Javadoc available
Method code:
public int getMapHeight() {
if (map.length == 0) {
// When the map size is 0*0 we get a
// java.lang.ArrayIndexOutOfBoundsException: 0
// if we don't have the check above.
return 0;
}
return map[0].length;
}
No outgoing methods.
jfreerails.world.top.WorldImpl.getMapWidth
Javadoc:
No Javadoc available
Method code:
public int getMapWidth() {
return map.length;
}
No outgoing methods.
jfreerails.world.top.WorldImpl.getNumberOfActiveEntities
Javadoc:
No Javadoc available
Method code:
public int getNumberOfActiveEntities(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
return activityLists.sizeD2(playerIndex);
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.getNumberOfPlayers
Javadoc:
No Javadoc available
Method code:
public int getNumberOfPlayers() {
return players.size();
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.getNumberOfTransactions
Javadoc:
No Javadoc available
Method code:
public int getNumberOfTransactions(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
return bankAccounts.sizeD2(playerIndex);
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.getPlayer
Javadoc:
No Javadoc available
Method code:
public Player getPlayer(int i) {
return players.get(i);
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.getTile
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable getTile(int x, int y) {
return map[x][y];
}
No outgoing methods.
jfreerails.world.top.WorldImpl.getTransaction
Javadoc:
No Javadoc available
Method code:
public Transaction getTransaction(FreerailsPrincipal p, int i) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = bankAccounts.get(playerIndex, i);
return tats.getT();
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.getTransactionAndTimeStamp
Javadoc:
No Javadoc available
Method code:
public Pair<Transaction, GameTime> getTransactionAndTimeStamp(
FreerailsPrincipal p, int i) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = bankAccounts.get(playerIndex, i);
return new Pair<Transaction, GameTime>(tats.getT(), tats.getTimeStamp());
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.getTransactionTimeStamp
Javadoc:
No Javadoc available
Method code:
public GameTime getTransactionTimeStamp(FreerailsPrincipal p, int i) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = bankAccounts.get(playerIndex, i);
return tats.getTimeStamp();
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.isPlayer
Javadoc:
No Javadoc available
Method code:
public boolean isPlayer(FreerailsPrincipal p) {
if (p.getWorldIndex() >= 0 && p.getWorldIndex() < players.size()) {
return true;
} else {
return false;
}
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.removeLast
Javadoc:
No Javadoc available
Method code:
public FreerailsSerializable removeLast(SKEY key) {
return sharedLists.removeLastD2(key.getKeyID());
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.removeLastActiveEntity
Javadoc:
No Javadoc available
Method code:
public Activity removeLastActiveEntity(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
int lastID = activityLists.sizeD2(playerIndex) - 1;
Activity act = activityLists.removeLastD3(playerIndex, lastID).act;
activityLists.removeLastD2(playerIndex);
return act;
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.removeLastActivity
Javadoc:
No Javadoc available
Method code:
public Activity removeLastActivity(FreerailsPrincipal p, int index) {
int playerIndex = p.getWorldIndex();
if (activityLists.sizeD3(playerIndex, index) < 2)
throw new IllegalStateException();
Activity act = activityLists.removeLastD3(playerIndex, index).act;
return act;
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.removeLastPlayer
Javadoc:
/** * Removes the last player to be added. * * @return the player that was removed. * @throws IllegalStateException * if any elements belonging to the player have not been * removed. */
Method code:
/**
* Removes the last player to be added.
*
* @return the player that was removed.
* @throws IllegalStateException
* if any elements belonging to the player have not been
* removed.
*/
public Player removeLastPlayer() {
int playerID = bankAccounts.removeLastD1();
while (lists.sizeD2(playerID) > 0)
lists.removeLastD2(playerID);
lists.removeLastD1();
currentBalance.removeLast();
activityLists.removeLastD1();
return players.removeLast();
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.removeLastTransaction
Javadoc:
No Javadoc available
Method code:
public Transaction removeLastTransaction(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = bankAccounts.removeLastD2(playerIndex);
Money oldBalance = currentBalance.get(playerIndex);
Money newBalance = new Money(oldBalance.getAmount()
- tats.getT().deltaCash().getAmount());
currentBalance.set(playerIndex, newBalance);
return tats.getT();
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.set
Javadoc:
No Javadoc available
Method code:
public void set(ITEM item, FreerailsSerializable element) {
items.set(item.getKeyID(), element);
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.setTile
Javadoc:
No Javadoc available
Method code:
public void setTile(int x, int y, FreerailsSerializable element) {
map[x][y] = element;
}
No outgoing methods.
jfreerails.world.top.WorldImpl.setTime
Javadoc:
/** * Sets the current time for the world. * * @param t the new GameTime value to set as the current time */
Method code:
public void setTime(GameTime t) {
time = t;
}
No outgoing methods.
jfreerails.world.top.WorldImpl.setupItems
Javadoc:
No Javadoc available
Method code:
void setupItems() {
this.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
time = new GameTime(0);
this.set(ITEM.ECONOMIC_CLIMATE, EconomicClimate.MODERATION);
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImpl.setupMap
Javadoc:
No Javadoc available
Method code:
public void setupMap(int mapWidth, int mapHeight) {
map = new FreerailsSerializable[mapWidth][mapHeight];
for (int x = 0; x < mapWidth; x++) {
for (int y = 0; y < mapHeight; y++) {
map[x][y] = FreerailsTile.NULL;
}
}
}
No outgoing methods.
jfreerails.world.top.WorldImpl.size
Javadoc:
No Javadoc available
Method code:
public int size(FreerailsPrincipal p, KEY key) {
int playerIndex = p.getWorldIndex();
return lists.sizeD3(playerIndex, key.getKeyID());
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImplTest.testActivityLists
Javadoc:
No Javadoc available
Method code:
public void testActivityLists() {
World w = new WorldImpl();
Player player = new Player("Name", 0);
w.addPlayer(player);
FreerailsPrincipal principal = player.getPrincipal();
// Test adding activities.
assertEquals(0, w.size(principal));
Activity act = new TestActivity(30);
int actIndex = w.addActiveEntity(principal, act);
assertEquals(0, actIndex);
assertEquals(1, w.size(principal));
actIndex = w.addActiveEntity(principal, act);
assertEquals(1, actIndex);
assertEquals(2, w.size(principal));
// Then removing them.
Activity expected = new TestActivity(30);
assertEquals(expected, act);
Activity actual = w.removeLastActiveEntity(principal);
assertEquals(actual, expected);
assertEquals(1, w.size(principal));
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImplTest.testBankAccount
Javadoc:
No Javadoc available
Method code:
public void testBankAccount(){
WorldImpl world = new WorldImpl();
Player p = new Player("Test", 0);
int playerID = world.addPlayer(p);
assertEquals(0, playerID);
FreerailsPrincipal fp = world.getPlayer(playerID).getPrincipal();
Transaction t = new AddItemTransaction(Category.BOND, 1, 2, new Money(100));
assertEquals(new Money(0), world.getCurrentBalance(fp));
world.addTransaction(fp, t);
assertEquals(1, world.getNumberOfTransactions(fp));
assertEquals(new Money(100), world.getCurrentBalance(fp));
Transaction t2 = world.getTransaction(fp, 0);
assertEquals(t, t2);
Transaction t3 = world.removeLastTransaction(fp);
assertEquals(t, t3);
assertEquals(new Money(0), world.getCurrentBalance(fp));
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImplTest.testBoundsContain
Javadoc:
No Javadoc available
Method code:
public void testBoundsContain(){
World w = new WorldImpl();
assertFalse(w.boundsContain(1, 1));
assertFalse(w.boundsContain(0, 0));
assertFalse(w.boundsContain(-1, -1));
w = new WorldImpl(5, 10);
assertTrue(w.boundsContain(0, 0));
assertTrue(w.boundsContain(4, 9));
assertFalse(w.boundsContain(-1, -1));
assertFalse(w.boundsContain(5, 10));
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImplTest.testConstructor
Javadoc:
No Javadoc available
Method code:
public void testConstructor() {
World w = new WorldImpl();
assertEquals("The width should be zero", 0, w.getMapWidth());
assertEquals("The height should be zero", 0, w.getMapHeight());
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImplTest.testDefensiveCopy
Javadoc:
/** * Tests that changing the object returned by defensiveCopy() does not alter * the world object that was copied. */
Method code:
/**
* Tests that changing the object returned by defensiveCopy() does not alter
* the world object that was copied.
*/
public void testDefensiveCopy() {
World original;
World copy;
original = new WorldImpl();
copy = original.defensiveCopy();
assertNotSame("The copies should be different objects.", original, copy);
assertEquals("The copies should be logically equal.", original, copy);
copy.add(SKEY.TERRAIN_TYPES, fs);
assertFalse(original.equals(copy));
assertFalse(copy.equals(original));
assertEquals(1, copy.size(SKEY.TERRAIN_TYPES));
assertEquals(0, original.size(SKEY.TERRAIN_TYPES));
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImplTest.testEquals
Javadoc:
No Javadoc available
Method code:
public void testEquals() {
World original;
World copy;
original = new WorldImpl();
copy = original.defensiveCopy();
Player player = new Player("Name", 0);
int index = copy.addPlayer(player);
assertEquals(index, 0);
assertFalse(copy.equals(original));
original.addPlayer(player);
assertEquals("The copies should be logically equal.", original, copy);
assertTrue(Utils.equalsBySerialization(original, copy));
Transaction t = new Receipt(new Money(100),
Transaction.Category.MISC_INCOME);
copy.addTransaction(player.getPrincipal(), t);
assertEquals(new Money(100), copy.getCurrentBalance(player
.getPrincipal()));
assertFalse(copy.equals(original));
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImplTest.testEquals2
Javadoc:
No Javadoc available
Method code:
public void testEquals2() {
World original;
World copy, copy2;
original = new WorldImpl();
copy = original.defensiveCopy();
copy2 = original.defensiveCopy();
// Test adding players.
Player a = new Player("Fred");
Player b = new Player("John");
original.addPlayer(a);
copy.addPlayer(b);
assertFalse(copy.equals(original));
copy.removeLastPlayer();
assertTrue(copy2.equals(copy));
copy.addPlayer(a);
assertTrue(copy.equals(original));
}
Outgoing Methods (calls):
jfreerails.world.top.WorldImplTest.testGet
Javadoc:
No Javadoc available
Method code:
public void testGet() {
WorldImpl w = new WorldImpl();
w.add(SKEY.TERRAIN_TYPES, fs);
assertEquals(w.get(SKEY.TERRAIN_TYPES, 0), fs);
}
Outgoing Methods (calls):
jfreerails.world.top.WorldIterator.getElement
Javadoc:
/** Returns the element the cursor is pointing to. */
Method code:
/** Returns the element the cursor is pointing to. */
FreerailsSerializable getElement();
No outgoing methods.
jfreerails.world.top.WorldIterator.getIndex
Javadoc:
/** * Returns the index of the element the cursor is pointing to. The value * returned is index you would need to use in * <code>World.get(KEY key, int index)</code> to retrieve the same element * as is returned by <code>getElement()</code> */
Method code:
/**
* Returns the index of the element the cursor is pointing to. The value
* returned is index you would need to use in
* <code>World.get(KEY key, int index)</code> to retrieve the same element
* as is returned by <code>getElement()</code>
*/
int getIndex();
No outgoing methods.
jfreerails.world.top.WorldIterator.getNaturalNumber
Javadoc:
/** * Returns the number of the row where the cursor is (the first row is 1). */
Method code:
/**
* Returns the number of the row where the cursor is (the first row is 1).
*/
int getNaturalNumber();
No outgoing methods.
jfreerails.world.top.WorldIterator.getRowID
Javadoc:
/** * Returns the number of the row where the cursor is (the first row is 0). */
Method code:
/**
* Returns the number of the row where the cursor is (the first row is 0).
*/
int getRowID();
No outgoing methods.
jfreerails.world.top.WorldIterator.gotoIndex
Javadoc:
/** * Moves the cursor to the specified index. * * @throws NoSuchElementException * if index out of range */
Method code:
/**
* Moves the cursor to the specified index.
*
* @throws NoSuchElementException
* if index out of range
*/
void gotoIndex(int i);
No outgoing methods.
jfreerails.world.top.WorldIterator.gotoRow
Javadoc:
/** Moves the cursor to the specified index. */
Method code:
/** Moves the cursor to the specified index. */
void gotoRow(int row);
No outgoing methods.
jfreerails.world.top.WorldIterator.next
Javadoc:
/** * Moves the cursor down one row from its current position. */
Method code:
/**
* Moves the cursor down one row from its current position.
*/
boolean next();
No outgoing methods.
jfreerails.world.top.WorldIterator.previous
Javadoc:
/** * Moves the cursor up one row from its current position. */
Method code:
/**
* Moves the cursor up one row from its current position.
*/
boolean previous();
No outgoing methods.
jfreerails.world.top.WorldIterator.reset
Javadoc:
/** * Moves the cursor to before the first element and updates any cached * values. */
Method code:
/**
* Moves the cursor to before the first element and updates any cached
* values.
*/
void reset();
No outgoing methods.
jfreerails.world.top.WorldIterator.size
Javadoc:
/** Returns the number of rows. */
Method code:
/** Returns the number of rows. */
int size();
No outgoing methods.
jfreerails.world.top.WorldListListener.itemAdded
Javadoc:
No Javadoc available
Method code:
void itemAdded(KEY key, int index, FreerailsPrincipal principal);
No outgoing methods.
jfreerails.world.top.WorldListListener.itemRemoved
Javadoc:
No Javadoc available
Method code:
void itemRemoved(KEY key, int index, FreerailsPrincipal principal);
No outgoing methods.
jfreerails.world.top.WorldListListener.listUpdated
Javadoc:
No Javadoc available
Method code:
void listUpdated(KEY key, int index, FreerailsPrincipal principal);
No outgoing methods.
jfreerails.world.top.WorldMapListener.tilesChanged
Javadoc:
/** * Called when tiles have changed. * * @param tilesChanged * rectangle containing the tiles that have change; all the * points contained by the rectangle must be within the map's * bounds. */
Method code:
/**
* Called when tiles have changed.
*
* @param tilesChanged
* rectangle containing the tiles that have change; all the
* points contained by the rectangle must be within the map's
* bounds.
*/
void tilesChanged(Rectangle tilesChanged);
No outgoing methods.
jfreerails.world.track.EightRotationsOfTrackPieceProducer.getRotations
Javadoc:
/** * The method that returns the rotations. * * @param trackBlueprint * A 9bit value that serves as the template. * @return An array of 8 9-bit values that have been generated by rotating * the template. */
Method code:
/**
* The method that returns the rotations.
*
* @param trackBlueprint
* A 9bit value that serves as the template.
* @return An array of 8 9-bit values that have been generated by rotating
* the template.
*/
public static int[] getRotations(int trackBlueprint) {
int trackTemplate = trackBlueprint;
int[] derivedTrackPieces = new int[8];
for (int i = 0; i < 8; i++) {
derivedTrackPieces[i] = trackTemplate;
boolean[][] trackTemplateBooleanArray = getTrackBooleanArray(trackTemplate);
trackTemplateBooleanArray = rotateTrackNodeClockwise(trackTemplateBooleanArray);
trackTemplate = getTrackGraphicID(trackTemplateBooleanArray);
}
return derivedTrackPieces;
}
Outgoing Methods (calls):
jfreerails.world.track.EightRotationsOfTrackPieceProducer.getTrackBooleanArray
Javadoc:
No Javadoc available
Method code:
private static boolean[][] getTrackBooleanArray(int trackGraphicInt) {
boolean[][] trackBooleanArray = new boolean[3][3];
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
if (((trackGraphicInt >> (3 * y + x)) & 1) == 1) {
trackBooleanArray[x][y] = true;
}
}
}
return trackBooleanArray;
}
No outgoing methods.
jfreerails.world.track.EightRotationsOfTrackPieceProducer.getTrackGraphicID
Javadoc:
No Javadoc available
Method code:
private static int getTrackGraphicID(boolean[][] railsList) {
int trackGraphicNumber = 0;
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
if (railsList[x][y]) {
trackGraphicNumber = trackGraphicNumber
| (1 << (3 * y + x));
}
}
}
return trackGraphicNumber;
}
No outgoing methods.
jfreerails.world.track.EightRotationsOfTrackPieceProducer.rotateTrackNodeClockwise
Javadoc:
No Javadoc available
Method code:
private static boolean[][] rotateTrackNodeClockwise(boolean[][] source) {
Point[][] grabValueFrom = new Point[3][];
grabValueFrom[0] = new Point[] { new Point(0, 1), new Point(0, 0),
new Point(1, 0) };
grabValueFrom[1] = new Point[] { new Point(0, 2), new Point(1, 1),
new Point(2, 0) };
grabValueFrom[2] = new Point[] { new Point(1, 2), new Point(2, 2),
new Point(2, 1) };
/*
* I think there is a neater way of doing this, let me know if you know
* it! Luke
*/
boolean[][] output = new boolean[3][3];
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
Point point = grabValueFrom[y][x];
/*
* y,x because of the way I defined grabValueFrom[][] above.
*/
output[x][y] = source[point.x][point.y];
}
}
return output;
}
No outgoing methods.
jfreerails.world.track.FreerailsTile.getInstance
Javadoc:
No Javadoc available
Method code:
public static FreerailsTile getInstance(int terrainType,
TrackPiece trackPiece) {
FreerailsTile tile = new FreerailsTile(terrainType, trackPiece);
if (instances.containsKey(tile)) {
return instances.get(tile);
}
instances.put(tile, tile);
return tile;
}
No outgoing methods.
jfreerails.world.track.FreerailsTile.getTerrainTypeID
Javadoc:
/** * Returns the terrain type ID of this tile. * The terrain type ID is an integer that represents the type of terrain * present on this tile in the game world. * * @return the terrain type ID as an integer */
Method code:
public int getTerrainTypeID() {
return terrainType;
}
No outgoing methods.
jfreerails.world.track.FreerailsTile.getTrackPiece
Javadoc:
No Javadoc available
Method code:
public TrackPiece getTrackPiece() {
return trackPiece;
}
No outgoing methods.
jfreerails.world.track.FreerailsTile.hasTrack
Javadoc:
No Javadoc available
Method code:
public boolean hasTrack(){
return trackPiece.getTrackTypeID() != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER;
}
Outgoing Methods (calls):
jfreerails.world.track.FreerailsTile.readResolve
Javadoc:
No Javadoc available
Method code:
private Object readResolve() throws ObjectStreamException {
if (instances.containsKey(this)) {
return instances.get(this);
}
instances.put(this, this);
return this;
}
No outgoing methods.
jfreerails.world.track.LegalTrackConfigurations.getLegalConfigurationsIterator
Javadoc:
No Javadoc available
Method code:
public Iterator<TrackConfiguration> getLegalConfigurationsIterator() {
return legalConfigs.iterator();
}
Outgoing Methods (calls):
jfreerails.world.track.LegalTrackConfigurations.getMaximumConsecutivePieces
Javadoc:
No Javadoc available
Method code:
public int getMaximumConsecutivePieces() {
return maximumConsecutivePieces;
}
No outgoing methods.
jfreerails.world.track.LegalTrackConfigurations.processTemplate
Javadoc:
No Javadoc available
Method code:
static private void processTemplate(String trackTemplateString,
HashSet<TrackConfiguration> temp) {
int trackTemplate = Integer.parseInt(trackTemplateString, 2);
// Check for invalid parameters.
if ((trackTemplate > 511) || (trackTemplate < 0)) {
throw new IllegalArgumentException("trackTemplate = "
+ trackTemplate + ", it should be in the range 0-511");
}
int[] rotationsOfTrackTemplate = EightRotationsOfTrackPieceProducer
.getRotations(trackTemplate);
for (int k = 0; k < rotationsOfTrackTemplate.length; k++) {
int i = rotationsOfTrackTemplate[k];
TrackConfiguration trackConfiguration = TrackConfiguration
.from9bitTemplate(i);
if (!temp.contains(trackConfiguration)) {
temp.add(trackConfiguration);
}
}
}
Outgoing Methods (calls):
jfreerails.world.track.LegalTrackConfigurations.trackConfigurationIsLegal
Javadoc:
No Javadoc available
Method code:
public boolean trackConfigurationIsLegal(
TrackConfiguration trackConfiguration) {
return legalConfigs.contains(trackConfiguration);
}
Outgoing Methods (calls):
jfreerails.world.track.LegalTrackConfigurationsTest.main
Javadoc:
No Javadoc available
Method code:
public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}
Outgoing Methods (calls):
jfreerails.world.track.LegalTrackConfigurationsTest.suite
Javadoc:
No Javadoc available
Method code:
public static Test suite() {
return new TestSuite(LegalTrackConfigurationsTest.class);
}
No outgoing methods.
jfreerails.world.track.LegalTrackConfigurationsTest.testTrackPieceIsLegal
Javadoc:
No Javadoc available
Method code:
public void testTrackPieceIsLegal() {
ArrayList<String> templates = new ArrayList<String>();
templates.add("000111000");
LegalTrackConfigurations ltc = new LegalTrackConfigurations(-1,
templates);
TrackConfiguration template = TrackConfiguration
.getFlatInstance("010010010");
assertEquals(true, ltc.trackConfigurationIsLegal(template));
template = TrackConfiguration.getFlatInstance("010111000");
assertEquals(false, ltc.trackConfigurationIsLegal(template));
}
Outgoing Methods (calls):
jfreerails.world.track.LegalTrackPlacement.canBuildOnThisTerrain
Javadoc:
No Javadoc available
Method code:
public boolean canBuildOnThisTerrain(TerrainType.Category terrainType) {
if (PlacementRule.ONLY_ON_THESE == placementRule) {
return terrainTypes.contains(terrainType);
}
return !terrainTypes.contains(terrainType);
}
Outgoing Methods (calls):
jfreerails.world.track.LegalTrackPlacement.getPlacementRule
Javadoc:
No Javadoc available
Method code:
public PlacementRule getPlacementRule() {
return placementRule;
}
No outgoing methods.
jfreerails.world.track.NullTrackPiece.getInstance
Javadoc:
No Javadoc available
Method code:
public static TrackPiece getInstance() {
return nullTrackPiece;
}
No outgoing methods.
jfreerails.world.track.NullTrackPiece.getOwnerID
Javadoc:
No Javadoc available
Method code:
public int getOwnerID() {
return NO_OWNER;
}
No outgoing methods.
jfreerails.world.track.NullTrackPiece.getTrackConfiguration
Javadoc:
No Javadoc available
Method code:
public TrackConfiguration getTrackConfiguration() {
return TrackConfiguration.from9bitTemplate(0);
}
Outgoing Methods (calls):
jfreerails.world.track.NullTrackPiece.getTrackGraphicID
Javadoc:
No Javadoc available
Method code:
public int getTrackGraphicID() {
return 0;
}
No outgoing methods.
jfreerails.world.track.NullTrackPiece.getTrackRule
Javadoc:
No Javadoc available
Method code:
public TrackRule getTrackRule() {
return NullTrackType.getInstance();
}
Outgoing Methods (calls):
jfreerails.world.track.NullTrackPiece.getTrackTypeID
Javadoc:
No Javadoc available
Method code:
public int getTrackTypeID() {
return NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER;
}
No outgoing methods.
jfreerails.world.track.NullTrackPiece.readResolve
Javadoc:
No Javadoc available
Method code:
private Object readResolve() throws ObjectStreamException {
return nullTrackPiece;
}
No outgoing methods.
jfreerails.world.track.NullTrackType.canBuildOnThisTerrainType
Javadoc:
No Javadoc available
Method code:
public boolean canBuildOnThisTerrainType(TerrainType.Category TerrainType) {
return true; // No track is possible anywhere.
}
No outgoing methods.
jfreerails.world.track.NullTrackType.compareTo
Javadoc:
No Javadoc available
Method code:
public int compareTo(TrackRule arg0) {
// TODO Auto-generated method stub
return 0;
}
No outgoing methods.
jfreerails.world.track.NullTrackType.getCategory
Javadoc:
No Javadoc available
Method code:
public TrackCategories getCategory() {
return TrackCategories.non;
}
No outgoing methods.
jfreerails.world.track.NullTrackType.getFixedCost
Javadoc:
No Javadoc available
Method code:
public Money getFixedCost() {
return Money.ZERO;
}
No outgoing methods.
jfreerails.world.track.NullTrackType.getInstance
Javadoc:
No Javadoc available
Method code:
public static NullTrackType getInstance() {
return nullTrackType;
}
No outgoing methods.
jfreerails.world.track.NullTrackType.getLegalConfigurationsIterator
Javadoc:
No Javadoc available
Method code:
public Iterator<TrackConfiguration> getLegalConfigurationsIterator() {
throw new UnsupportedOperationException("Method not implemented yet!");
}
No outgoing methods.
jfreerails.world.track.NullTrackType.getLegalRoutes
Javadoc:
No Javadoc available
Method code:
public Step[] getLegalRoutes(
jfreerails.world.common.Step directionComingFrom) {
return new Step[0];
}
No outgoing methods.
jfreerails.world.track.NullTrackType.getMaintenanceCost
Javadoc:
No Javadoc available
Method code:
public Money getMaintenanceCost() {
return new Money(0);
}
No outgoing methods.
jfreerails.world.track.NullTrackType.getMaximumConsecutivePieces
Javadoc:
No Javadoc available
Method code:
public int getMaximumConsecutivePieces() {
return -1;
}
No outgoing methods.
jfreerails.world.track.NullTrackType.getPrice
Javadoc:
No Javadoc available
Method code:
public Money getPrice() {
return new Money(0);
}
No outgoing methods.
jfreerails.world.track.NullTrackType.getStationRadius
Javadoc:
No Javadoc available
Method code:
public int getStationRadius() {
return 0;
}
No outgoing methods.
jfreerails.world.track.NullTrackType.getTrackPiece
Javadoc:
No Javadoc available
Method code:
public TrackPiece getTrackPiece(TrackConfiguration config, int owner) {
throw new UnsupportedOperationException("Method not implemented yet!");
}
No outgoing methods.
jfreerails.world.track.NullTrackType.getTypeName
Javadoc:
No Javadoc available
Method code:
public String getTypeName() {
return "NullTrackType";
}
No outgoing methods.
jfreerails.world.track.NullTrackType.isDouble
Javadoc:
No Javadoc available
Method code:
public boolean isDouble() {
return false;
}
No outgoing methods.
jfreerails.world.track.NullTrackType.isStation
Javadoc:
No Javadoc available
Method code:
public boolean isStation() {
return false;
}
No outgoing methods.
jfreerails.world.track.NullTrackType.readResolve
Javadoc:
No Javadoc available
Method code:
private Object readResolve() throws ObjectStreamException {
return nullTrackType;
}
No outgoing methods.
jfreerails.world.track.NullTrackType.testTrackPieceLegality
Javadoc:
No Javadoc available
Method code:
public boolean testTrackPieceLegality(int trackTemplateToTest) {
if (trackTemplateToTest != 0) {
return false;
}
return true;
}
No outgoing methods.
jfreerails.world.track.NullTrackType.trackPieceIsLegal
Javadoc:
No Javadoc available
Method code:
public boolean trackPieceIsLegal(TrackConfiguration config) {
return testTrackPieceLegality(config.getTrackGraphicsID());
}
Outgoing Methods (calls):
jfreerails.world.track.TrackConfiguration.add
Javadoc:
/** * @return the superposition of two track templates */
Method code:
/**
* @return the superposition of two track templates
*/
public static TrackConfiguration add(FlatTrackTemplate c,
FlatTrackTemplate v) {
/*
* int x=v.getX()+1; int y=v.getY()+1; int oldTemplate
* =c.getTrackGraphicsNumber(); int newTemplate = oldTemplate | (1 <<
* (3 * y + x));
*/
int newTemplate = c.get9bitTemplate() | v.get9bitTemplate();
return from9bitTemplate(newTemplate);
}
Outgoing Methods (calls):
jfreerails.world.track.TrackConfiguration.contains
Javadoc:
No Javadoc available
Method code:
public boolean contains(int trackTemplate) {
if ((trackTemplate | this.configuration) == this.configuration) {
return true;
}
return false;
}
No outgoing methods.
jfreerails.world.track.TrackConfiguration.from9bitTemplate
Javadoc:
No Javadoc available
Method code:
public static TrackConfiguration from9bitTemplate(int i) {
return flatTrackConfigurations.get(i);
}
No outgoing methods.
jfreerails.world.track.TrackConfiguration.get8bitTemplate
Javadoc:
No Javadoc available
Method code:
public int get8bitTemplate() {
int newTemplate = 0;
Step[] vectors = Step.getList();
for (int i = 0; i < vectors.length; i++) {
if (this.contains(vectors[i])) {
newTemplate = newTemplate | vectors[i].get8bitTemplate();
}
}
return newTemplate;
}
Outgoing Methods (calls):
jfreerails.world.track.TrackConfiguration.get9bitTemplate
Javadoc:
/** * @return an int representing this track configuration. */
Method code:
/**
* @return an int representing this track configuration.
*/
public int get9bitTemplate() {
return configuration;
}
No outgoing methods.
jfreerails.world.track.TrackConfiguration.getFlatInstance
Javadoc:
No Javadoc available
Method code:
public static TrackConfiguration getFlatInstance(String trackTemplate) {
int i = TrackConfiguration.stringTemplate2Int(trackTemplate);
return (flatTrackConfigurations.get(i));
}
Outgoing Methods (calls):
jfreerails.world.track.TrackConfiguration.getLength
Javadoc:
/** * Returns the length of track used in this configuration. Used to calculate * the cost of building track. */
Method code:
/**
* Returns the length of track used in this configuration. Used to calculate
* the cost of building track.
*/
public int getLength() {
return length;
}
No outgoing methods.
jfreerails.world.track.TrackConfiguration.getPossibleConfigurationsIterator
Javadoc:
No Javadoc available
Method code:
public Iterator getPossibleConfigurationsIterator() {
return flatTrackConfigurations.iterator();
}
No outgoing methods.
jfreerails.world.track.TrackConfiguration.getTrackGraphicsID
Javadoc:
No Javadoc available
Method code:
public int getTrackGraphicsID() {
return configuration;
}
No outgoing methods.
jfreerails.world.track.TrackConfiguration.readResolve
Javadoc:
No Javadoc available
Method code:
private Object readResolve() throws ObjectStreamException {
return TrackConfiguration.from9bitTemplate(this.configuration);
}
Outgoing Methods (calls):
jfreerails.world.track.TrackConfiguration.setupConfigurations
Javadoc:
No Javadoc available
Method code:
private static ArrayList<TrackConfiguration> setupConfigurations() {
ArrayList<TrackConfiguration> configurations = new ArrayList<TrackConfiguration>(
512);
for (int i = 0; i < 512; i++) {
configurations.add(i, new TrackConfiguration(i));
}
return configurations;
}
No outgoing methods.
jfreerails.world.track.TrackConfiguration.stringTemplate2Int
Javadoc:
No Javadoc available
Method code:
public static int stringTemplate2Int(String templateString) {
// Hack - so that result is as expected by earlier written code.
StringBuffer strb = new StringBuffer(templateString);
strb = strb.reverse();
templateString = strb.toString();
// End of hack
return Integer.parseInt(templateString, 2);
}
No outgoing methods.
jfreerails.world.track.TrackConfiguration.subtract
Javadoc:
/** * @return the TrackConfiguration representing the track section c minus the * track sections represented by v. */
Method code:
/**
* @return the TrackConfiguration representing the track section c minus the
* track sections represented by v.
*/
public static TrackConfiguration subtract(FlatTrackTemplate c,
FlatTrackTemplate v) {
/*
* int x=v.getX()+1; int y=v.getY()+1; int oldTemplate
* =c.getTrackGraphicsNumber(); int newTemplate = oldTemplate ^ (1 <<
* (3 * y + x));
*/
int newTemplate = c.get9bitTemplate() & (~v.get9bitTemplate());
return from9bitTemplate(newTemplate);
}
Outgoing Methods (calls):
jfreerails.world.track.TrackConfigurationTest.main
Javadoc:
No Javadoc available
Method code:
public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}
Outgoing Methods (calls):
jfreerails.world.track.TrackConfigurationTest.suite
Javadoc:
No Javadoc available
Method code:
public static Test suite() {
TestSuite suite = new TestSuite(TrackConfigurationTest.class);
return suite;
}
No outgoing methods.
jfreerails.world.track.TrackConfigurationTest.testAdd
Javadoc:
No Javadoc available
Method code:
public void testAdd() {
TrackConfiguration a = TrackConfiguration.getFlatInstance("000010000");
TrackConfiguration b = TrackConfiguration.add(a, Step.NORTH_WEST);
assertEquals(TrackConfiguration.getFlatInstance("100010000"), b);
assertEquals(false, a == b);
}
Outgoing Methods (calls):
jfreerails.world.track.TrackConfigurationTest.testGet8And9bitTemplate
Javadoc:
No Javadoc available
Method code:
public void testGet8And9bitTemplate() {
for (int i = 0; i < 512; i++) {
TrackConfiguration tc = TrackConfiguration.from9bitTemplate(i);
assertEquals(i, tc.get9bitTemplate());
}
for (Step v : Step.getList()) {
TrackConfiguration tc = TrackConfiguration.getFlatInstance(v);
assertEquals(v.get9bitTemplate(), tc.get9bitTemplate());
assertEquals(v.get8bitTemplate(), tc.get8bitTemplate());
TrackConfiguration tc2 = TrackConfiguration.from9bitTemplate(v
.get9bitTemplate());
assertEquals(tc, tc2);
}
}
Outgoing Methods (calls):
jfreerails.world.track.TrackConfigurationTest.testGetLength
Javadoc:
No Javadoc available
Method code:
public void testGetLength() {
TrackConfiguration a = TrackConfiguration.getFlatInstance("010010000");
TrackConfiguration b = TrackConfiguration.getFlatInstance("010010010");
assertEquals(30, a.getLength());
assertEquals(60, b.getLength());
}
Outgoing Methods (calls):
jfreerails.world.track.TrackConfigurationTest.testSubtract
Javadoc:
No Javadoc available
Method code:
public void testSubtract() {
TrackConfiguration a = TrackConfiguration.getFlatInstance("100010000");
TrackConfiguration b = TrackConfiguration.subtract(a, Step.NORTH_WEST);
assertEquals(TrackConfiguration.getFlatInstance("000010000"), b);
}
Outgoing Methods (calls):
jfreerails.world.track.TrackConfigurationTest.testToString
Javadoc:
No Javadoc available
Method code:
public void testToString() {
TrackConfiguration a = TrackConfiguration.getFlatInstance("100010000");
assertEquals("tile center, north west", a.toString());
a = TrackConfiguration.getFlatInstance(Step.NORTH_WEST);
assertEquals("no tile center, north west", a.toString());
a = TrackConfiguration.getFlatInstance("000010000");
assertEquals("tile center", a.toString());
a = TrackConfiguration.getFlatInstance("000000000");
assertEquals("no tile center", a.toString());
// Check that no two track configurations have the same String
// representation.
HashSet<String> strings = new HashSet<String>();
for (int i = 0; i < 512; i++) {
TrackConfiguration test = TrackConfiguration.from9bitTemplate(i);
String toString = test.toString();
if (strings.contains(toString)) {
fail(toString + " " + i);
}
strings.add(toString);
}
}
Outgoing Methods (calls):
jfreerails.world.track.TrackPiece.getOwnerID
Javadoc:
No Javadoc available
Method code:
int getOwnerID();
No outgoing methods.
jfreerails.world.track.TrackPiece.getTrackConfiguration
Javadoc:
No Javadoc available
Method code:
TrackConfiguration getTrackConfiguration();
No outgoing methods.
jfreerails.world.track.TrackPiece.getTrackGraphicID
Javadoc:
No Javadoc available
Method code:
int getTrackGraphicID();
No outgoing methods.
jfreerails.world.track.TrackPiece.getTrackRule
Javadoc:
No Javadoc available
Method code:
TrackRule getTrackRule();
No outgoing methods.
jfreerails.world.track.TrackPiece.getTrackTypeID
Javadoc:
No Javadoc available
Method code:
int getTrackTypeID();
No outgoing methods.
jfreerails.world.track.TrackPieceImpl.getOwnerID
Javadoc:
No Javadoc available
Method code:
public int getOwnerID() {
return ownerID;
}
No outgoing methods.
jfreerails.world.track.TrackPieceImpl.getTrackConfiguration
Javadoc:
No Javadoc available
Method code:
public TrackConfiguration getTrackConfiguration() {
return configuration;
}
No outgoing methods.
jfreerails.world.track.TrackPieceImpl.getTrackGraphicID
Javadoc:
No Javadoc available
Method code:
public int getTrackGraphicID() {
return configuration.getTrackGraphicsID();
}
Outgoing Methods (calls):
jfreerails.world.track.TrackPieceImpl.getTrackRule
Javadoc:
No Javadoc available
Method code:
public TrackRule getTrackRule() {
return trackType;
}
No outgoing methods.
jfreerails.world.track.TrackPieceImpl.getTrackTypeID
Javadoc:
No Javadoc available
Method code:
public int getTrackTypeID() {
return ruleNumber;
}
No outgoing methods.
jfreerails.world.track.TrackPieceImplTest.setUp
Javadoc:
No Javadoc available
Method code:
@Override
protected void setUp() throws Exception {
w = MapFixtureFactory2.getCopy();
}
Outgoing Methods (calls):
jfreerails.world.track.TrackPieceImplTest.testEqualsObject
Javadoc:
No Javadoc available
Method code:
public void testEqualsObject() {
TrackConfiguration tc1 = TrackConfiguration.getFlatInstance(Step.NORTH);
TrackRule rule0 = (TrackRule) w.get(SKEY.TRACK_RULES, 0);
TrackRule rule4 = (TrackRule) w.get(SKEY.TRACK_RULES, 4);
TrackPieceImpl tp1 = new TrackPieceImpl(tc1, rule0, 0, 0);
assertEquals(tp1, tp1);
TrackPieceImpl tp2 = new TrackPieceImpl(tc1, rule4, 0, 4);
assertFalse(tp1.equals(tp2));
TrackPieceImpl tp1Clone = (TrackPieceImpl) Utils
.cloneBySerialisation(tp1);
assertEquals(tp1, tp1Clone);
}
Outgoing Methods (calls):
jfreerails.world.track.TrackRule.canBuildOnThisTerrainType
Javadoc:
No Javadoc available
Method code:
boolean canBuildOnThisTerrainType(TerrainType.Category TerrainType);
No outgoing methods.
jfreerails.world.track.TrackRule.getCategory
Javadoc:
No Javadoc available
Method code:
TrackCategories getCategory();
No outgoing methods.
jfreerails.world.track.TrackRule.getFixedCost
Javadoc:
No Javadoc available
Method code:
Money getFixedCost();
No outgoing methods.
jfreerails.world.track.TrackRule.getLegalConfigurationsIterator
Javadoc:
No Javadoc available
Method code:
Iterator<TrackConfiguration> getLegalConfigurationsIterator();
No outgoing methods.
jfreerails.world.track.TrackRule.getLegalRoutes
Javadoc:
No Javadoc available
Method code:
Step[] getLegalRoutes(Step directionComingFrom);
No outgoing methods.
jfreerails.world.track.TrackRule.getMaintenanceCost
Javadoc:
No Javadoc available
Method code:
Money getMaintenanceCost();
No outgoing methods.
jfreerails.world.track.TrackRule.getMaximumConsecutivePieces
Javadoc:
No Javadoc available
Method code:
int getMaximumConsecutivePieces();
No outgoing methods.
jfreerails.world.track.TrackRule.getPrice
Javadoc:
No Javadoc available
Method code:
Money getPrice();
No outgoing methods.
jfreerails.world.track.TrackRule.getStationRadius
Javadoc:
No Javadoc available
Method code:
int getStationRadius();
No outgoing methods.
jfreerails.world.track.TrackRule.getTypeName
Javadoc:
No Javadoc available
Method code:
String getTypeName();
No outgoing methods.
jfreerails.world.track.TrackRule.isDouble
Javadoc:
No Javadoc available
Method code:
boolean isDouble();
No outgoing methods.
jfreerails.world.track.TrackRule.isStation
Javadoc:
No Javadoc available
Method code:
boolean isStation();
No outgoing methods.
jfreerails.world.track.TrackRule.testTrackPieceLegality
Javadoc:
No Javadoc available
Method code:
boolean testTrackPieceLegality(int a9bitTemplate);
No outgoing methods.
jfreerails.world.track.TrackRule.trackPieceIsLegal
Javadoc:
/** * Checks whether the track piece configured in the given TrackConfiguration is legally placed * according to the rules defined by this TrackRule subclass. * * @param config the configuration of the track piece to be validated * @return true if the track piece is legally placed, false otherwise */
Method code:
boolean trackPieceIsLegal(TrackConfiguration config);
No outgoing methods.
jfreerails.world.track.TrackRuleImpl.canBuildOnThisTerrainType
Javadoc:
No Javadoc available
Method code:
public boolean canBuildOnThisTerrainType(TerrainType.Category TerrainType) {
return legalTrackPlacement.canBuildOnThisTerrain(TerrainType);
}
Outgoing Methods (calls):
jfreerails.world.track.TrackRuleImpl.compareTo
Javadoc:
/** * If the specified object is a track rule, comparison is by category then * price. */
Method code:
/**
* If the specified object is a track rule, comparison is by category then
* price.
*/
public int compareTo(TrackRule otherRule) {
int comp = otherRule.getCategory().compareTo(getCategory());
if (comp != 0) {
return -comp;
}
long dPrice = this.properties.getPrice().getAmount()
- otherRule.getPrice().getAmount();
return (int) dPrice;
}
Outgoing Methods (calls):
jfreerails.world.track.TrackRuleImpl.getCategory
Javadoc:
No Javadoc available
Method code:
public TrackRule.TrackCategories getCategory() {
return properties.getCategory();
}
Outgoing Methods (calls):
jfreerails.world.track.TrackRuleImpl.getFixedCost
Javadoc:
No Javadoc available
Method code:
public Money getFixedCost() {
return properties.getFixedCost();
}
Outgoing Methods (calls):
jfreerails.world.track.TrackRuleImpl.getLegalConfigurations
Javadoc:
No Javadoc available
Method code:
public LegalTrackConfigurations getLegalConfigurations() {
return legalConfigurations;
}
No outgoing methods.
jfreerails.world.track.TrackRuleImpl.getLegalConfigurationsIterator
Javadoc:
No Javadoc available
Method code:
public Iterator<TrackConfiguration> getLegalConfigurationsIterator() {
return legalConfigurations.getLegalConfigurationsIterator();
}
Outgoing Methods (calls):
jfreerails.world.track.TrackRuleImpl.getLegalRoutes
Javadoc:
No Javadoc available
Method code:
public Step[] getLegalRoutes(Step directionComingFrom) {
// TODO add code..
return null;
}
No outgoing methods.
jfreerails.world.track.TrackRuleImpl.getLegalTrackPlacement
Javadoc:
No Javadoc available
Method code:
public LegalTrackPlacement getLegalTrackPlacement() {
return legalTrackPlacement;
}
No outgoing methods.
jfreerails.world.track.TrackRuleImpl.getMaintenanceCost
Javadoc:
No Javadoc available
Method code:
public Money getMaintenanceCost() {
return properties.getMaintenanceCost();
}
Outgoing Methods (calls):
jfreerails.world.track.TrackRuleImpl.getMaximumConsecutivePieces
Javadoc:
No Javadoc available
Method code:
public int getMaximumConsecutivePieces() {
return legalConfigurations.getMaximumConsecutivePieces();
}
Outgoing Methods (calls):
jfreerails.world.track.TrackRuleImpl.getPrice
Javadoc:
No Javadoc available
Method code:
public Money getPrice() {
return this.properties.getPrice();
}
Outgoing Methods (calls):
jfreerails.world.track.TrackRuleImpl.getProperties
Javadoc:
No Javadoc available
Method code:
public TrackRuleProperties getProperties() {
return properties;
}
No outgoing methods.
jfreerails.world.track.TrackRuleImpl.getStationRadius
Javadoc:
No Javadoc available
Method code:
public int getStationRadius() {
return this.properties.getStationRadius();
}
Outgoing Methods (calls):
jfreerails.world.track.TrackRuleImpl.getTypeName
Javadoc:
No Javadoc available
Method code:
public String getTypeName() {
return properties.getTypeName();
}
Outgoing Methods (calls):
jfreerails.world.track.TrackRuleImpl.isDouble
Javadoc:
No Javadoc available
Method code:
public boolean isDouble() {
return properties.isEnableDoubleTrack();
}
Outgoing Methods (calls):
jfreerails.world.track.TrackRuleImpl.isStation
Javadoc:
No Javadoc available
Method code:
public boolean isStation() {
return properties.isStation();
}
Outgoing Methods (calls):
jfreerails.world.track.TrackRuleImpl.testTrackPieceLegality
Javadoc:
No Javadoc available
Method code:
public boolean testTrackPieceLegality(int trackTemplateToTest) {
TrackConfiguration trackConfiguration = TrackConfiguration
.from9bitTemplate(trackTemplateToTest);
return legalConfigurations
.trackConfigurationIsLegal(trackConfiguration);
}
Outgoing Methods (calls):
jfreerails.world.track.TrackRuleImpl.trackPieceIsLegal
Javadoc:
No Javadoc available
Method code:
public boolean trackPieceIsLegal(TrackConfiguration config) {
return legalConfigurations.trackConfigurationIsLegal(config);
}
Outgoing Methods (calls):
jfreerails.world.track.TrackRuleProperties.getCategory
Javadoc:
No Javadoc available
Method code:
public TrackRule.TrackCategories getCategory() {
return category;
}
No outgoing methods.
jfreerails.world.track.TrackRuleProperties.getFixedCost
Javadoc:
No Javadoc available
Method code:
public Money getFixedCost() {
return fixedCost;
}
No outgoing methods.
jfreerails.world.track.TrackRuleProperties.getMaintenanceCost
Javadoc:
No Javadoc available
Method code:
public Money getMaintenanceCost() {
return maintenanceCost;
}
No outgoing methods.
jfreerails.world.track.TrackRuleProperties.getPrice
Javadoc:
No Javadoc available
Method code:
public Money getPrice() {
return price;
}
No outgoing methods.
jfreerails.world.track.TrackRuleProperties.getRGBvalue
Javadoc:
No Javadoc available
Method code:
private int getRGBvalue() {
return rGBvalue;
}
No outgoing methods.
jfreerails.world.track.TrackRuleProperties.getStationRadius
Javadoc:
No Javadoc available
Method code:
public int getStationRadius() {
return stationRadius;
}
No outgoing methods.
jfreerails.world.track.TrackRuleProperties.getTypeName
Javadoc:
No Javadoc available
Method code:
public String getTypeName() {
return typeName;
}
No outgoing methods.
jfreerails.world.track.TrackRuleProperties.isEnableDoubleTrack
Javadoc:
No Javadoc available
Method code:
public boolean isEnableDoubleTrack() {
return enableDoubleTrack;
}
No outgoing methods.
jfreerails.world.track.TrackRuleProperties.isStation
Javadoc:
No Javadoc available
Method code:
public boolean isStation() {
return category.equals(TrackRule.TrackCategories.station);
}
No outgoing methods.
jfreerails.world.track.TrackSection.tileA
Javadoc:
No Javadoc available
Method code:
public ImPoint tileA(){
return tile;
}
No outgoing methods.
jfreerails.world.track.TrackSection.tileB
Javadoc:
No Javadoc available
Method code:
public ImPoint tileB(){
return Step.move(tile, step);
}
Outgoing Methods (calls):
jfreerails.world.track.TrackSectionTest.testEqualsObject
Javadoc:
No Javadoc available
Method code:
public void testEqualsObject() {
TrackSection a = new TrackSection(Step.EAST, new ImPoint(10, 5));
TrackSection b = new TrackSection(Step.WEST, new ImPoint(11, 5));
assertEquals(a, a);
assertEquals(b, b);
assertEquals(a, b);
assertEquals(b, a);
}
No outgoing methods.
jfreerails.world.train.CompositeSpeedAgainstTime.calcA
Javadoc:
No Javadoc available
Method code:
public double calcA(double t) {
checkT(t);
TandI tai = getIndex(t);
SpeedAgainstTime acc = values.get(tai.i);
return acc.calcA(tai.offset);
}
Outgoing Methods (calls):
jfreerails.world.train.CompositeSpeedAgainstTime.calcS
Javadoc:
No Javadoc available
Method code:
public double calcS(double t) {
if(t == this.finalT) return this.finalS;
checkT(t);
TandI tai = getIndex(t);
double s = 0;
for (int i = 0; i < tai.i; i++) {
SpeedAgainstTime acc = values.get(i);
s += acc.getS();
}
SpeedAgainstTime acc = values.get(tai.i);
if(tai.offset >= acc.getT()){
//Note, it is possible for tai.offset > acc.getT()
//even though we called checkT(t) above
s += acc.getS();
}else{
s += acc.calcS(tai.offset);
}
return s;
}
Outgoing Methods (calls):
jfreerails.world.train.CompositeSpeedAgainstTime.calcT
Javadoc:
No Javadoc available
Method code:
public double calcT(double s) {
if(s == this.finalS) return this.finalT;
if (s > finalS)
throw new IllegalArgumentException(String.valueOf(s));
double sSoFar = 0;
double tSoFar = 0;
int i = 0;
SpeedAgainstTime acc = values.get(i);
while ((sSoFar + acc.getS()) < s) {
sSoFar += acc.getS();
tSoFar += acc.getT();
i++;
acc = values.get(i);
}
double sOffset = s - sSoFar;
if(sOffset >= acc.getS()){
tSoFar += acc.getT();
}else{
tSoFar += acc.calcT(sOffset);
}
return tSoFar;
}
Outgoing Methods (calls):
jfreerails.world.train.CompositeSpeedAgainstTime.calcV
Javadoc:
No Javadoc available
Method code:
public double calcV(double t) {
checkT(t);
TandI tai = getIndex(t);
SpeedAgainstTime acc = values.get(tai.i);
return acc.calcV(tai.offset);
}
Outgoing Methods (calls):
jfreerails.world.train.CompositeSpeedAgainstTime.checkT
Javadoc:
No Javadoc available
Method code:
void checkT(double t) {
if (t < 0d || t > finalT)
throw new IllegalArgumentException("t="+t+", but duration="+finalT);
}
No outgoing methods.
jfreerails.world.train.CompositeSpeedAgainstTime.duration
Javadoc:
No Javadoc available
Method code:
public double duration() {
return finalT;
}
No outgoing methods.
jfreerails.world.train.CompositeSpeedAgainstTime.getIndex
Javadoc:
No Javadoc available
Method code:
private TandI getIndex(double t) {
checkT(t);
double tSoFar = 0;
for (int i = 0; i < values.size(); i++) {
SpeedAgainstTime acc = values.get(i);
if (t <= (tSoFar + acc.getT())) {
double offset = t - tSoFar;
return new TandI(i, offset);
}
tSoFar += acc.getT();
}
// Should never happen since we call checkT() above!
throw new IllegalStateException(String.valueOf(t));
}
Outgoing Methods (calls):
jfreerails.world.train.CompositeSpeedAgainstTime.getS
Javadoc:
No Javadoc available
Method code:
public double getS() {
return finalS;
}
No outgoing methods.
jfreerails.world.train.CompositeSpeedAgainstTime.getState
Javadoc:
No Javadoc available
Method code:
public SpeedTimeAndStatus getState(final double dt) {
checkT(dt);
double acceleration;
SpeedTimeAndStatus.TrainActivity activity = SpeedTimeAndStatus.TrainActivity.READY;
double s = 0;
double speed;
TandI tai = getIndex(dt);
SpeedAgainstTime acc = values.get(tai.i);
speed = acc.calcV(tai.offset);
acceleration = acc.calcA(tai.offset);
s = acc.calcS(tai.offset);
return new SpeedTimeAndStatus(acceleration, activity, dt, s, speed);
}
Outgoing Methods (calls):
jfreerails.world.train.CompositeSpeedAgainstTime.getT
Javadoc:
No Javadoc available
Method code:
public double getT() {
return finalT;
}
No outgoing methods.
jfreerails.world.train.CompositeSpeedAgainstTimeTest.testBounds
Javadoc:
No Javadoc available
Method code:
public void testBounds(){
SpeedAgainstTime sat = ConstAcc.uas(10, 2, 400d);
CompositeSpeedAgainstTime csat = new CompositeSpeedAgainstTime(sat);
double t = csat.duration();
double t2 = csat.calcT(400d);
assertEquals(t, t2);
double s = csat.calcS(t);
assertEquals(400d, s);
double t3 = csat.calcT(0d);
assertEquals(0d, t3);
}
Outgoing Methods (calls):
jfreerails.world.train.CompositeSpeedAgainstTimeTest.testContract
Javadoc:
No Javadoc available
Method code:
public void testContract(){
Random r = new Random(123);
for(int i = 0 ; i < 1000; i++){
int numberOfParts = r.nextInt(10) + 1;
SpeedAgainstTime[] parts = new SpeedAgainstTime[numberOfParts];
for(int j = 0; j < numberOfParts; j++){
parts[j] = ConstAcc.uat(r.nextDouble(), r.nextDouble(), r.nextDouble());
}
CompositeSpeedAgainstTime csat = new CompositeSpeedAgainstTime(parts);
ConstAccTest.checkContract(csat);
}
}
Outgoing Methods (calls):
jfreerails.world.train.ConstAcc.calcA
Javadoc:
No Javadoc available
Method code:
public double calcA(double t) {
validateT(t);
return a;
}
Outgoing Methods (calls):
jfreerails.world.train.ConstAcc.calcS
Javadoc:
No Javadoc available
Method code:
public double calcS(double t) {
if(t == finalT) return finalS;
validateT(t);
double ds = u * t + a * t * t / 2;
ds = Math.min(ds, finalS);
return ds;
}
Outgoing Methods (calls):
jfreerails.world.train.ConstAcc.calcT
Javadoc:
No Javadoc available
Method code:
private static double calcT(double u, double a, double s) {
// Note, Utils.solveQuadratic throws an exception if a == 0
return a == 0 ? s / u : Utils.solveQuadratic(a * 0.5d, u, -s);
}
Outgoing Methods (calls):
jfreerails.world.train.ConstAcc.calcV
Javadoc:
No Javadoc available
Method code:
public double calcV(double t) {
validateT(t);
return u + a * t;
}
Outgoing Methods (calls):
jfreerails.world.train.ConstAcc.getS
Javadoc:
No Javadoc available
Method code:
public double getS() {
return finalS;
}
No outgoing methods.
jfreerails.world.train.ConstAcc.getT
Javadoc:
No Javadoc available
Method code:
public double getT() {
return finalT;
}
No outgoing methods.
jfreerails.world.train.ConstAcc.uas
Javadoc:
No Javadoc available
Method code:
public static ConstAcc uas(double u, double a, double s) {
double t = calcT(u, a, s);
return new ConstAcc(a, t, u, s);
}
Outgoing Methods (calls):
jfreerails.world.train.ConstAcc.uat
Javadoc:
No Javadoc available
Method code:
public static ConstAcc uat(double u, double a, double t) {
double s = u * t + a * t * t / 2;
return new ConstAcc(a, t, u, s);
}
No outgoing methods.
jfreerails.world.train.ConstAcc.validateT
Javadoc:
No Javadoc available
Method code:
private void validateT(double t){
if(t < 0 || t > finalT)
throw new IllegalArgumentException("("+t+" < 0 || "+t+" > "+finalT+")");
}
No outgoing methods.
jfreerails.world.train.ConstAccTest.checkCalcSCalcVandCalcA
Javadoc:
No Javadoc available
Method code:
private static void checkCalcSCalcVandCalcA(SpeedAgainstTime sat, double t){
boolean exceptionExpected = (t < 0) || ( t > sat.getT());
try{
double actualS = sat.calcS(t);
assertTrue(actualS >= 0);
assertTrue(actualS <= sat.getS());
assertFalse(exceptionExpected);
}catch (IllegalArgumentException e) {
assertTrue(exceptionExpected);
}
//Also check getV and getA
try{
double v = sat.calcV(t);
assertTrue(v >= 0);
assertFalse(exceptionExpected);
}catch (IllegalArgumentException e) {
assertTrue(exceptionExpected);
}
try{
sat.calcA(t);
assertFalse(exceptionExpected);
}catch (IllegalArgumentException e) {
assertTrue(exceptionExpected);
}
}
Outgoing Methods (calls):
jfreerails.world.train.ConstAccTest.checkCalcT
Javadoc:
No Javadoc available
Method code:
private static void checkCalcT(SpeedAgainstTime sat, double s){
boolean exceptionExpected = (s < 0) || ( s > sat.getS());
try{
double actualT = sat.calcT(s);
assertTrue(actualT >= 0);
assertTrue(actualT <= sat.getT());
assertFalse(exceptionExpected);
}catch (IllegalArgumentException e) {
assertTrue(exceptionExpected);
}
}
Outgoing Methods (calls):
jfreerails.world.train.ConstAccTest.checkContract
Javadoc:
/** Checks the specified object satisfies the contract defined by * the interface SpeedAgainstTime. */
Method code:
/** Checks the specified object satisfies the contract defined by
* the interface SpeedAgainstTime.
*/
public static void checkContract(SpeedAgainstTime sat){
double s = sat.getS();
double ulps = Math.ulp(s);
double t = sat.getT();
double ulpt = Math.ulp(t);
//Check calcS()
checkCalcSCalcVandCalcA(sat, 0 - Double.MIN_VALUE);
checkCalcSCalcVandCalcA(sat, t + ulpt);
checkCalcSCalcVandCalcA(sat, 0 + Double.MIN_VALUE);
checkCalcSCalcVandCalcA(sat, t - ulpt);
for(double d = 0; d < 1d; d += 0.1d){
checkCalcSCalcVandCalcA(sat, t * d);
}
double actualS = sat.calcS(0);
assertEquals(0d, actualS);
actualS = sat.calcS(t);
assertEquals(s, actualS);
//Check calcT()
checkCalcT(sat, 0 - Double.MIN_VALUE);
checkCalcT(sat, s + ulps);
checkCalcT(sat, 0 + Double.MIN_VALUE);
checkCalcT(sat, s - ulps);
for(double d = 0; d < 1d; d += 0.1d){
checkCalcT(sat, s * d);
}
double actualT = sat.calcT(0);
assertEquals(0d, actualT);
actualT = sat.calcT(s);
assertEquals(t, actualT);
}
Outgoing Methods (calls):
jfreerails.world.train.ConstAccTest.testContract
Javadoc:
No Javadoc available
Method code:
public void testContract(){
Random r = new Random(88);
for(int i = 0; i < 1000; i++){
ConstAcc acc1 = ConstAcc.uat(r.nextDouble(), r.nextDouble(), r.nextDouble());
checkContract(acc1);
ConstAcc acc2 = ConstAcc.uas(r.nextDouble(), r.nextDouble(), r.nextDouble());
checkContract(acc2);
}
}
Outgoing Methods (calls):
jfreerails.world.train.ConstAccTest.testEquals
Javadoc:
No Javadoc available
Method code:
public void testEquals() {
SpeedAgainstTime acc1 = ConstAcc.uat(0, 10, 4);
SpeedAgainstTime acc2 = ConstAcc.uat(0, 10, 4);
assertEquals(acc1, acc2);
}
Outgoing Methods (calls):
jfreerails.world.train.ConstAccTest.testTandS
Javadoc:
No Javadoc available
Method code:
public void testTandS() {
SpeedAgainstTime acc1 = ConstAcc.uat(0, 10, 5);
double s = acc1.getS();
SpeedAgainstTime acc2 = ConstAcc.uas(0, 10, s);
assertEquals(acc1, acc2);
acc1 = ConstAcc.uat(10, 0, 5);
assertEquals(50, acc1.getS(), 0.00001);
acc2 = ConstAcc.uas(10, 0, acc1.getS());
assertEquals(acc1, acc2);
}
Outgoing Methods (calls):
jfreerails.world.train.EngineType.getEngineTypeName
Javadoc:
No Javadoc available
Method code:
public String getEngineTypeName() {
return engineTypeName;
}
No outgoing methods.
jfreerails.world.train.EngineType.getMaintenance
Javadoc:
No Javadoc available
Method code:
public Money getMaintenance() {
return maintenance;
}
No outgoing methods.
jfreerails.world.train.EngineType.getMaxSpeed
Javadoc:
No Javadoc available
Method code:
public int getMaxSpeed() {
return maxSpeed;
}
No outgoing methods.
jfreerails.world.train.EngineType.getPowerAtDrawbar
Javadoc:
No Javadoc available
Method code:
public int getPowerAtDrawbar() {
return powerAtDrawbar;
}
No outgoing methods.
jfreerails.world.train.EngineType.getPrice
Javadoc:
No Javadoc available
Method code:
public Money getPrice() {
return price;
}
No outgoing methods.
jfreerails.world.train.ImmutableSchedule.autoConsist
Javadoc:
No Javadoc available
Method code:
public boolean autoConsist() {
TrainOrdersModel order = orders.get(getOrderToGoto());
return order.autoConsist;
}
Outgoing Methods (calls):
jfreerails.world.train.ImmutableSchedule.getNextScheduledOrder
Javadoc:
No Javadoc available
Method code:
public int getNextScheduledOrder() {
return this.nextScheduledOrder;
}
No outgoing methods.
jfreerails.world.train.ImmutableSchedule.getNumOrders
Javadoc:
No Javadoc available
Method code:
public int getNumOrders() {
return orders.size();
}
Outgoing Methods (calls):
jfreerails.world.train.ImmutableSchedule.getOrder
Javadoc:
No Javadoc available
Method code:
public TrainOrdersModel getOrder(int i) {
return orders.get(i);
}
Outgoing Methods (calls):
jfreerails.world.train.ImmutableSchedule.getOrderToGoto
Javadoc:
No Javadoc available
Method code:
public int getOrderToGoto() {
return hasPriorityOrders ? 0 : nextScheduledOrder;
}
No outgoing methods.
jfreerails.world.train.ImmutableSchedule.getStationToGoto
Javadoc:
/** * Returns the station ID that the train is ordered to go to. * Returns -1 if there is no such order. * * @return the station ID of the order to go to, or -1 if no such order exists */
Method code:
public int getStationToGoto() {
int orderToGoto = getOrderToGoto();
if (-1 == orderToGoto) {
return -1;
}
TrainOrdersModel order = orders.get(orderToGoto);
return order.getStationID();
}
Outgoing Methods (calls):
jfreerails.world.train.ImmutableSchedule.getWagonsToAdd
Javadoc:
No Javadoc available
Method code:
public ImInts getWagonsToAdd() {
TrainOrdersModel order = orders.get(getOrderToGoto());
return order.consist;
}
Outgoing Methods (calls):
jfreerails.world.train.ImmutableSchedule.hasPriorityOrders
Javadoc:
No Javadoc available
Method code:
public boolean hasPriorityOrders() {
return hasPriorityOrders;
}
No outgoing methods.
jfreerails.world.train.ImmutableSchedule.stopsAtStation
Javadoc:
No Javadoc available
Method code:
public boolean stopsAtStation(int stationNumber) {
for (int i = 0; i < this.getNumOrders(); i++) {
TrainOrdersModel order = this.getOrder(i);
if (order.getStationID() == stationNumber) {
return true;
}
}
return false;
}
Outgoing Methods (calls):
jfreerails.world.train.IntLineTest.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
junit.textui.TestRunner.run(IntLineTest.class);
}
No outgoing methods.
jfreerails.world.train.IntLineTest.testGetLength
Javadoc:
No Javadoc available
Method code:
public void testGetLength() {
IntLine line = new IntLine(0, 0, 100, 0);
assertEquals(100, line.getLength(), 0.1);
}
Outgoing Methods (calls):
jfreerails.world.train.MutableSchedule.addOrder
Javadoc:
/** * Inserts an order at the specified position. Note you must call * setPriorityOrders() to set the priority orders. */
Method code:
/**
* Inserts an order at the specified position. Note you must call
* setPriorityOrders() to set the priority orders.
*/
public void addOrder(int orderNumber, TrainOrdersModel order) {
orders.add(orderNumber, order);
if (nextScheduledOrder >= orderNumber) {
nextScheduledOrder++;
}
if (-1 == nextScheduledOrder && 0 < numberOfScheduledStops()) {
nextScheduledOrder = firstScheduleStop();
}
}
Outgoing Methods (calls):
jfreerails.world.train.MutableSchedule.autoConsist
Javadoc:
No Javadoc available
Method code:
public boolean autoConsist() {
return orders.get(nextScheduledOrder).autoConsist;
}
No outgoing methods.
jfreerails.world.train.MutableSchedule.canAddOrder
Javadoc:
No Javadoc available
Method code:
public boolean canAddOrder() {
int max = hasPriorityOrders ? MAXIMUM_NUMBER_OF_ORDER + 1
: MAXIMUM_NUMBER_OF_ORDER;
return max > getNumOrders();
}
Outgoing Methods (calls):
jfreerails.world.train.MutableSchedule.canPullUp
Javadoc:
No Javadoc available
Method code:
public boolean canPullUp(int orderNumber) {
boolean isAlreadyAtTop = 0 == orderNumber;
boolean isPriorityOrdersAbove = (orderNumber == 1 && this.hasPriorityOrders);
return !isAlreadyAtTop && !isPriorityOrdersAbove;
}
No outgoing methods.
jfreerails.world.train.MutableSchedule.canPushDown
Javadoc:
No Javadoc available
Method code:
public boolean canPushDown(int orderNumber) {
boolean isOrderPriorityOrders = (orderNumber == 0 && this.hasPriorityOrders);
boolean isAlreadyAtBottom = orderNumber == this.orders.size() - 1;
return !isOrderPriorityOrders && !isAlreadyAtBottom;
}
No outgoing methods.
jfreerails.world.train.MutableSchedule.canSetGotoStation
Javadoc:
No Javadoc available
Method code:
public boolean canSetGotoStation(int orderNumber) {
return !(orderNumber == 0 && hasPriorityOrders);
}
No outgoing methods.
jfreerails.world.train.MutableSchedule.firstScheduleStop
Javadoc:
No Javadoc available
Method code:
private int firstScheduleStop() {
return hasPriorityOrders ? 1 : 0;
}
No outgoing methods.
jfreerails.world.train.MutableSchedule.getNextScheduledOrder
Javadoc:
No Javadoc available
Method code:
public int getNextScheduledOrder() {
return this.nextScheduledOrder;
}
No outgoing methods.
jfreerails.world.train.MutableSchedule.getNumOrders
Javadoc:
/** * Returns number of non priority orders + number of priority orders. * * @return Number of orders. */
Method code:
/**
* Returns number of non priority orders + number of priority orders.
*
* @return Number of orders.
*/
public int getNumOrders() {
return orders.size();
}
No outgoing methods.
jfreerails.world.train.MutableSchedule.getOrder
Javadoc:
No Javadoc available
Method code:
public TrainOrdersModel getOrder(int i) {
return orders.get(i);
}
No outgoing methods.
jfreerails.world.train.MutableSchedule.getOrderToGoto
Javadoc:
/** Returns the number of the order the train is currently carry out. */
Method code:
/** Returns the number of the order the train is currently carry out. */
public int getOrderToGoto() {
return nextScheduledOrder;
}
No outgoing methods.
jfreerails.world.train.MutableSchedule.getStationToGoto
Javadoc:
/** * Returns the station number of the next station the train is scheduled to * stop at. */
Method code:
/**
* Returns the station number of the next station the train is scheduled to
* stop at.
*/
public int getStationToGoto() {
return orders.get(nextScheduledOrder).getStationID();
}
Outgoing Methods (calls):
jfreerails.world.train.MutableSchedule.getWagonsToAdd
Javadoc:
/** Returns the wagons to add at the next scheduled stop. */
Method code:
/** Returns the wagons to add at the next scheduled stop. */
public ImInts getWagonsToAdd() {
return orders.get(nextScheduledOrder).getConsist();
}
Outgoing Methods (calls):
jfreerails.world.train.MutableSchedule.gotoNextStation
Javadoc:
/** * If there are no priority orders, sets the station to goto to the next * station in the list of orders or if there are no more stations, the first * station in the list. If priority orders are set, the priority orders * orders are removed from the schedule and the goto station is not changed. */
Method code:
/**
* If there are no priority orders, sets the station to goto to the next
* station in the list of orders or if there are no more stations, the first
* station in the list. If priority orders are set, the priority orders
* orders are removed from the schedule and the goto station is not changed.
*/
public void gotoNextStation() {
if (hasPriorityOrders) {
if (nextScheduledOrder != PRIORITY_ORDERS) {
removeOrder(PRIORITY_ORDERS);
return;
}
}
nextScheduledOrder++;
if (orders.size() <= nextScheduledOrder) {
nextScheduledOrder = 0;
}
}
Outgoing Methods (calls):
jfreerails.world.train.MutableSchedule.hasPriorityOrders
Javadoc:
No Javadoc available
Method code:
public boolean hasPriorityOrders() {
return this.hasPriorityOrders;
}
No outgoing methods.
jfreerails.world.train.MutableSchedule.numberOfScheduledStops
Javadoc:
No Javadoc available
Method code:
private int numberOfScheduledStops() {
return orders.size() - firstScheduleStop();
}
Outgoing Methods (calls):
jfreerails.world.train.MutableSchedule.pullUp
Javadoc:
No Javadoc available
Method code:
public void pullUp(int orderNumber) {
if (!canPullUp(orderNumber)) {
throw new IllegalArgumentException(String.valueOf(orderNumber));
}
boolean isGoingToThisStation = getOrderToGoto() == orderNumber;
TrainOrdersModel order = getOrder(orderNumber);
removeOrder(orderNumber);
addOrder(orderNumber - 1, order);
if (isGoingToThisStation) {
setOrderToGoto(orderNumber - 1);
}
}
Outgoing Methods (calls):
jfreerails.world.train.MutableSchedule.pushDown
Javadoc:
No Javadoc available
Method code:
public void pushDown(int orderNumber) {
if (!canPushDown(orderNumber)) {
throw new IllegalArgumentException(String.valueOf(orderNumber));
}
boolean isGoingToThisStation = getOrderToGoto() == orderNumber;
TrainOrdersModel order = getOrder(orderNumber);
removeOrder(orderNumber);
addOrder(orderNumber + 1, order);
if (isGoingToThisStation) {
setOrderToGoto(orderNumber + 1);
}
}
Outgoing Methods (calls):
jfreerails.world.train.MutableSchedule.removeAllStopsAtStation
Javadoc:
No Javadoc available
Method code:
public void removeAllStopsAtStation(int stationNumber) {
int i = 0;
while (i < this.getNumOrders()) {
TrainOrdersModel order = this.getOrder(i);
if (order.getStationID() == stationNumber) {
this.removeOrder(i);
} else {
i++;
}
}
}
Outgoing Methods (calls):
jfreerails.world.train.MutableSchedule.removeOrder
Javadoc:
/** * Removes the order at the specified position. */
Method code:
/**
* Removes the order at the specified position.
*/
public void removeOrder(int orderNumber) {
if (PRIORITY_ORDERS == orderNumber && hasPriorityOrders) {
// If we are removing the priority stop.
hasPriorityOrders = false;
}
orders.remove(orderNumber);
/* shift current station down */
if (nextScheduledOrder > orderNumber) {
nextScheduledOrder--;
}
if (orders.size() <= nextScheduledOrder) {
nextScheduledOrder = firstScheduleStop();
}
if (0 == numberOfScheduledStops()) {
nextScheduledOrder = -1;
}
}
Outgoing Methods (calls):
jfreerails.world.train.MutableSchedule.setOrder
Javadoc:
No Javadoc available
Method code:
public void setOrder(int orderNumber, TrainOrdersModel order) {
if (orderNumber >= orders.size()) {
orders.add(order);
} else {
orders.set(orderNumber, order);
}
}
No outgoing methods.
jfreerails.world.train.MutableSchedule.setOrderToGoto
Javadoc:
No Javadoc available
Method code:
public void setOrderToGoto(int i) {
if (i < 0 || i >= orders.size()) {
throw new IllegalArgumentException(String.valueOf(i));
}
nextScheduledOrder = i;
}
No outgoing methods.
jfreerails.world.train.MutableSchedule.setPriorityOrders
Javadoc:
No Javadoc available
Method code:
public void setPriorityOrders(TrainOrdersModel order) {
if (hasPriorityOrders) {
// Replace existing priority orders.
orders.set(PRIORITY_ORDERS, order);
} else {
// Insert priority orders at position 0;
hasPriorityOrders = true;
orders.add(PRIORITY_ORDERS, order);
nextScheduledOrder++;
}
}
No outgoing methods.
jfreerails.world.train.MutableSchedule.toImmutableSchedule
Javadoc:
No Javadoc available
Method code:
public ImmutableSchedule toImmutableSchedule() {
TrainOrdersModel[] ordersArray = new TrainOrdersModel[orders.size()];
for (int i = 0; i < ordersArray.length; i++) {
ordersArray[i] = orders.get(i);
}
return new ImmutableSchedule(ordersArray, this.nextScheduledOrder,
this.hasPriorityOrders);
}
No outgoing methods.
jfreerails.world.train.MutableScheduleTest.test1
Javadoc:
No Javadoc available
Method code:
public void test1() {
TrainOrdersModel order0 = new TrainOrdersModel(0, null, false, false);
TrainOrdersModel order1 = new TrainOrdersModel(1, null, false, false);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
int station2Goto = s.getStationToGoto();
assertEquals(0, station2Goto);
// ImmutableSchedule is = s.toImmutableSchedule();
//
// int i = is.getStationToGoto();
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTiles.addSteps
Javadoc:
No Javadoc available
Method code:
public PathOnTiles addSteps(Step... newSteps) {
int oldLength = vectors.size();
Step[] newPath = new Step[oldLength + newSteps.length];
for (int i = 0; i < oldLength; i++) {
newPath[i] = vectors.get(i);
}
for (int i = 0; i < newSteps.length; i++) {
newPath[i + oldLength] = newSteps[i];
}
return new PathOnTiles(start, newPath);
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTiles.getDistance
Javadoc:
/** * Calculates the total distance covered by the first 'steps' steps in the path. * * @param steps the number of steps to include in the distance calculation. * @return the accumulated distance from the first 'steps' steps. */
Method code:
public double getDistance(int steps) {
double distanceSoFar = 0;
for (int i = 0; i < steps; i++) {
Step v = vectors.get(i);
distanceSoFar += v.getLength();
}
return distanceSoFar;
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTiles.getFinalPosition
Javadoc:
No Javadoc available
Method code:
public PositionOnTrack getFinalPosition() {
int x = start.x;
int y = start.y;
for (int i = 0; i < vectors.size(); i++) {
Step v = vectors.get(i);
x += v.deltaX;
y += v.deltaY;
}
int i = vectors.size() - 1;
Step finalStep = vectors.get(i);
PositionOnTrack p = PositionOnTrack.createFacing(x, y, finalStep);
return p;
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTiles.getPoint
Javadoc:
/** * Returns the coordinates of the point you would be standing at if you * walked the specified distance along the path from the start point. * * @throws IllegalArgumentException * if distance < 0 * @throws IllegalArgumentException * if distance > getLength() */
Method code:
/**
* Returns the coordinates of the point you would be standing at if you
* walked the specified distance along the path from the start point.
*
* @throws IllegalArgumentException
* if distance < 0
* @throws IllegalArgumentException
* if distance > getLength()
*/
public ImPoint getPoint(double distance) {
if (0 > distance)
throw new IllegalArgumentException("distance:" + distance + " < 0");
int x = start.x * TILE_DIAMETER + TILE_DIAMETER / 2;
int y = start.y * TILE_DIAMETER + TILE_DIAMETER / 2;
double distanceSoFar = 0;
for (int i = 0; i < vectors.size(); i++) {
Step v = vectors.get(i);
distanceSoFar += v.getLength();
x += v.deltaX * TILE_DIAMETER;
y += v.deltaY * TILE_DIAMETER;
if (distanceSoFar == distance) {
return new ImPoint(x, y);
}
if (distanceSoFar > distance) {
double excess = distanceSoFar - distance;
x -= v.deltaX * TILE_DIAMETER * excess / v.getLength();
y -= v.deltaY * TILE_DIAMETER * excess / v.getLength();
return new ImPoint(x, y);
}
}
throw new IllegalArgumentException("distance > getLength()");
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTiles.getStart
Javadoc:
No Javadoc available
Method code:
public ImPoint getStart() {
return start;
}
No outgoing methods.
jfreerails.world.train.PathOnTiles.getStep
Javadoc:
No Javadoc available
Method code:
public Step getStep(int i) {
return vectors.get(i);
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTiles.getStepIndex
Javadoc:
/** * Returns the index of the step that takes the distance travelled over the * specified distance. * * @throws IllegalArgumentException * if distance < 0 * @throws IllegalArgumentException * if distance > getLength() */
Method code:
/**
* Returns the index of the step that takes the distance travelled over the
* specified distance.
*
* @throws IllegalArgumentException
* if distance < 0
* @throws IllegalArgumentException
* if distance > getLength()
*/
public int getStepIndex(int distance) {
if (0 > distance)
throw new IllegalArgumentException("distance < 0");
int distanceSoFar = 0;
for (int i = 0; i < vectors.size(); i++) {
Step v = vectors.get(i);
distanceSoFar += v.getLength();
if (distanceSoFar >= distance)
return i;
}
throw new IllegalArgumentException("distance > getLength()");
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTiles.getTotalDistance
Javadoc:
/** * Returns the distance you would travel if you walked the all the way along * the path. */
Method code:
/**
* Returns the distance you would travel if you walked the all the way along
* the path.
*/
public double getTotalDistance() {
return getDistance(vectors.size());
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTiles.steps
Javadoc:
No Javadoc available
Method code:
public int steps() {
return vectors.size();
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTiles.subPath
Javadoc:
/** * Returns a FreerailsPathIterator that exposes a sub section of the path * this object represents. * * @throws IllegalArgumentException * if offset < 0 * @throws IllegalArgumentException * if length <= 0 * @throws IllegalArgumentException * if offset + length > getLength() * */
Method code:
/**
* Returns a FreerailsPathIterator that exposes a sub section of the path
* this object represents.
*
* @throws IllegalArgumentException
* if offset < 0
* @throws IllegalArgumentException
* if length <= 0
* @throws IllegalArgumentException
* if offset + length > getLength()
*
*/
public FreerailsPathIterator subPath(double offset, double length) {
if (offset < 0)
throw new IllegalArgumentException();
if (length <= 0)
throw new IllegalArgumentException();
if ((offset + length) > getTotalDistance())
throw new IllegalArgumentException(offset +" + "+ length+" > " +getTotalDistance());
final LinkedList<ImPoint> points = new LinkedList<ImPoint>();
ImPoint tile = getStart();
int tileX = tile.x;
int tileY = tile.y;
int distanceSoFar = 0;
for (int i = 0; i < vectors.size(); i++) {
if (distanceSoFar > offset + length) {
break;
}
if (distanceSoFar >= offset) {
int x = TILE_DIAMETER / 2 + TILE_DIAMETER * tileX;
int y = TILE_DIAMETER / 2 + TILE_DIAMETER * tileY;
points.add(new ImPoint(x, y));
}
Step v = vectors.get(i);
tileX += v.deltaX;
tileY += v.deltaY;
distanceSoFar += v.getLength();
}
ImPoint first = getPoint(offset);
if (points.size() == 0) {
points.addFirst(first);
} else if (!points.getFirst().equals(first)) {
points.addFirst(first);
}
ImPoint last = getPoint(offset + length);
if (!points.getLast().equals(last)) {
points.addLast(last);
}
return new FreerailsPathIterator() {
private static final long serialVersionUID = 1L;
int index = 0;
public boolean hasNext() {
return (index + 1) < points.size();
}
public void nextSegment(IntLine line) {
if (!hasNext()) {
throw new NoSuchElementException();
}
ImPoint a = points.get(index);
line.x1 = a.x;
line.y1 = a.y;
ImPoint b = points.get(index + 1);
line.x2 = b.x;
line.y2 = b.y;
index++;
}
};
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTiles.tiles
Javadoc:
No Javadoc available
Method code:
public Iterator<ImPoint> tiles() {
return new Iterator<ImPoint>() {
int index = 0;
ImPoint next = start;
public boolean hasNext() {
return next != null;
}
public ImPoint next() {
if (next == null)
throw new NoSuchElementException();
ImPoint returnValue = next;
int x = next.x;
int y = next.y;
if (index < vectors.size()) {
Step s = vectors.get(index);
x += s.deltaX;
y += s.deltaY;
next = new ImPoint(x, y);
} else {
next = null;
}
index++;
return returnValue;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTilesTest.checkPath
Javadoc:
No Javadoc available
Method code:
private void checkPath(FreerailsPathIterator pathIt, ImPoint[] expected) {
IntLine line = new IntLine();
for (int i = 0; i < expected.length - 1; i++) {
assertTrue(pathIt.hasNext());
pathIt.nextSegment(line);
assertEquals(expected[i].x, line.x1);
assertEquals(expected[i + 1].x, line.x2);
assertEquals(expected[i].y, line.y1);
assertEquals(expected[i + 1].y, line.y2);
}
assertFalse(pathIt.hasNext());
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTilesTest.testGetLength
Javadoc:
No Javadoc available
Method code:
public void testGetLength() {
ImPoint start = new ImPoint();
Step[] vectors = new Step[] { EAST, EAST, EAST };
PathOnTiles path = new PathOnTiles(start, vectors);
assertEquals(3 * Step.TILE_DIAMETER, path.getTotalDistance(), 0.001);
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTilesTest.testGetPoint
Javadoc:
/** * Tests the getPoint method of the PathOnTiles class to ensure it correctly * returns the expected ImPoint at various steps along the path. */
Method code:
public void testGetPoint() {
ImPoint start = new ImPoint();
Step[] vectors = new Step[] { EAST, EAST, EAST };
PathOnTiles path = new PathOnTiles(start, vectors);
ImPoint expected = new ImPoint(15, 15);
ImPoint actual = path.getPoint(0);
assertEquals(expected, actual);
expected = new ImPoint(45, 15);
actual = path.getPoint(30);
assertEquals(expected, actual);
expected = new ImPoint(60, 15);
actual = path.getPoint(45);
assertEquals(expected, actual);
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTilesTest.testGetStepIndex
Javadoc:
No Javadoc available
Method code:
public void testGetStepIndex() {
ImPoint start = new ImPoint();
Step[] vectors = new Step[] { SOUTH_EAST, EAST, EAST };
PathOnTiles path = new PathOnTiles(start, vectors);
assertEquals(0, path.getStepIndex(0));
assertEquals(0, path.getStepIndex(1));
assertEquals(0, path.getStepIndex(30));
assertEquals(1, path.getStepIndex(60));
assertEquals(2, path.getStepIndex(90));
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTilesTest.testPathOnTiles
Javadoc:
No Javadoc available
Method code:
public void testPathOnTiles() {
ImPoint start = null;
Step[] vectors = null;
assertTrue(throwsException(start, vectors));
start = new ImPoint();
assertTrue(throwsException(start, vectors));
vectors = new Step[] { null, null };
assertTrue(throwsException(start, vectors));
vectors = new Step[] { NORTH, SOUTH };
assertFalse(throwsException(start, vectors));
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTilesTest.testSubPath
Javadoc:
No Javadoc available
Method code:
public void testSubPath() {
ImPoint start = new ImPoint();
Step[] vectors = new Step[] { EAST, EAST, EAST };
PathOnTiles path = new PathOnTiles(start, vectors);
// First check.
FreerailsPathIterator pathIt = path.subPath(0, path.getTotalDistance());
ImPoint[] expected = { new ImPoint(15, 15), new ImPoint(45, 15),
new ImPoint(75, 15), new ImPoint(105, 15) };
checkPath(pathIt, expected);
// Second check
pathIt = path.subPath(3, path.getTotalDistance() - 3);
expected = new ImPoint[] { new ImPoint(18, 15), new ImPoint(45, 15),
new ImPoint(75, 15), new ImPoint(105, 15) };
checkPath(pathIt, expected);
// 3rd check
double i = path.getTotalDistance() - 10;
pathIt = path.subPath(3, i);
expected = new ImPoint[] { new ImPoint(18, 15), new ImPoint(45, 15),
new ImPoint(75, 15), new ImPoint(98, 15) };
checkPath(pathIt, expected);
// 4th check, with a path just 1 tile long.
start = new ImPoint(5, 5);
vectors = new Step[] { SOUTH_WEST };
path = new PathOnTiles(start, vectors);
pathIt = path.subPath(18, 24);
IntLine line = new IntLine();
assertTrue(pathIt.hasNext());
pathIt.nextSegment(line);
assertEquals("The length of the train.", 24, line.getLength(), 1d);
assertFalse(pathIt.hasNext());
// 5th check, same as 2nd but with different starting position.
vectors = new Step[] { EAST, EAST, EAST };
start = new ImPoint(4, 7);
path = new PathOnTiles(start, vectors);
pathIt = path.subPath(3, path.getTotalDistance() - 3);
expected = new ImPoint[] { new ImPoint(18, 15), new ImPoint(45, 15),
new ImPoint(75, 15), new ImPoint(105, 15) };
for (int j = 0; j < expected.length; j++) {
int x = expected[j].x + start.x * TILE_DIAMETER;
int y = expected[j].y + start.y * TILE_DIAMETER;
expected[j] = new ImPoint(x, y);
}
// for (ImPoint point : expected) {
// point.x += start.x * TILE_DIAMETER;
// point.y += start.y * TILE_DIAMETER;
// }
checkPath(pathIt, expected);
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTilesTest.testTiles
Javadoc:
No Javadoc available
Method code:
public void testTiles() {
PathOnTiles path = new PathOnTiles(new ImPoint(5, 5), SOUTH_WEST,
NORTH_EAST);
Iterator<ImPoint> it = path.tiles();
assertEquals(new ImPoint(5, 5), it.next());
assertEquals(new ImPoint(4, 6), it.next());
assertEquals(new ImPoint(5, 5), it.next());
assertFalse(it.hasNext());
}
Outgoing Methods (calls):
jfreerails.world.train.PathOnTilesTest.throwsException
Javadoc:
No Javadoc available
Method code:
boolean throwsException(ImPoint start, Step[] vectors) {
try {
new PathOnTiles(start, vectors);
return false;
} catch (Exception e) {
return true;
}
}
No outgoing methods.
jfreerails.world.train.PathWalker.canStepForward
Javadoc:
/** * Returns true if we have not reached the end of the path. */
Method code:
/**
* Returns true if we have not reached the end of the path.
*/
boolean canStepForward();
No outgoing methods.
jfreerails.world.train.PathWalker.stepForward
Javadoc:
/** * Moves this path walker forward by the specified distance along the path * and returns a path iterator to retrieve the section of the path travelled * during this move. */
Method code:
/**
* Moves this path walker forward by the specified distance along the path
* and returns a path iterator to retrieve the section of the path travelled
* during this move.
*/
void stepForward(double distance);
No outgoing methods.
jfreerails.world.train.PathWalkerImpl.canStepForward
Javadoc:
/** * @return true if we still have more of the current segment, or more * segments left. */
Method code:
/**
* @return true if we still have more of the current segment, or more
* segments left.
*/
public boolean canStepForward() {
if (currentSegment.getLength() > distanceAlongCurrentSegment) {
return true;
} else if (it.hasNext()) {
return true;
} else {
return false;
}
}
Outgoing Methods (calls):
jfreerails.world.train.PathWalkerImpl.endAtSegmentEnd
Javadoc:
No Javadoc available
Method code:
private void endAtSegmentEnd(IntLine line,
double remainingDistanceAlongCurrentSegment) {
line.x2 = this.currentSegment.x2;
line.y2 = this.currentSegment.y2;
this.distanceOfThisStepRemaining -= remainingDistanceAlongCurrentSegment;
distanceAlongCurrentSegment = this.currentSegment.getLength();
}
Outgoing Methods (calls):
jfreerails.world.train.PathWalkerImpl.endInMiddleOfSegment
Javadoc:
/** * Updates the end point coordinates (x2, y2) of the provided line segment * to reflect the position where the movement ended in the middle of the current segment. * This method adjusts the line's end point based on the accumulated distance along the segment. * * @param line The line segment whose end point (x2, y2) is to be updated * to represent the position where the movement ended. */
Method code:
private void endInMiddleOfSegment(IntLine line) {
distanceAlongCurrentSegment += distanceOfThisStepRemaining;
distanceOfThisStepRemaining = 0;
line.x2 = getCoordinateOnSegment(distanceAlongCurrentSegment,
currentSegment.x1, currentSegment.x2);
line.y2 = getCoordinateOnSegment(distanceAlongCurrentSegment,
currentSegment.y1, currentSegment.y2);
}
Outgoing Methods (calls):
jfreerails.world.train.PathWalkerImpl.getCoordinateOnSegment
Javadoc:
No Javadoc available
Method code:
private int getCoordinateOnSegment(double distanceAlongSegment,
int coordinate1, int coordinate2) {
double segmentLength = this.currentSegment.getLength();
double delta = 0;
if (0 != segmentLength) {
delta = (coordinate2 - coordinate1) * distanceAlongSegment
/ segmentLength;
}
return coordinate1 + (int) delta;
}
Outgoing Methods (calls):
jfreerails.world.train.PathWalkerImpl.hasNext
Javadoc:
/** * @return true if there is still some distance to go along this path */
Method code:
/**
* @return true if there is still some distance to go along this path
*/
public boolean hasNext() {
if (0 == distanceOfThisStepRemaining) {
return false;
} else if (distanceAlongCurrentSegment < currentSegment.getLength()) {
return true;
} else if (it.hasNext()) {
return true;
} else {
return false;
}
}
Outgoing Methods (calls):
jfreerails.world.train.PathWalkerImpl.nextSegment
Javadoc:
No Javadoc available
Method code:
public void nextSegment(IntLine line) {
if (!hasNext()) {
throw new NoSuchElementException();
}
// If we are at the end of the current segment, start a new one.
if (currentSegment.getLength() <= distanceAlongCurrentSegment) {
startNewSegment(line);
} else {
startInMiddleOfSegment(line);
}
double remainingDistanceAlongCurrentSegment = currentSegment
.getLength()
- distanceAlongCurrentSegment;
if (distanceOfThisStepRemaining > remainingDistanceAlongCurrentSegment) {
endAtSegmentEnd(line, remainingDistanceAlongCurrentSegment);
} else {
endInMiddleOfSegment(line);
}
/*
* Sanity check: the first point of the last line should equal the
* second point of the current line.
*
*/
if (!beforeFirst) {
if (line.x1 != this.lastX) {
throw new IllegalStateException();
}
if (line.y1 != this.lastY) {
throw new IllegalStateException();
}
}
this.lastX = line.x2;
this.lastY = line.y2;
beforeFirst = false;
return;
}
Outgoing Methods (calls):
jfreerails.world.train.PathWalkerImpl.startInMiddleOfSegment
Javadoc:
No Javadoc available
Method code:
private void startInMiddleOfSegment(IntLine line) {
line.x1 = getCoordinateOnSegment(distanceAlongCurrentSegment,
currentSegment.x1, currentSegment.x2);
line.y1 = getCoordinateOnSegment(distanceAlongCurrentSegment,
currentSegment.y1, currentSegment.y2);
}
Outgoing Methods (calls):
jfreerails.world.train.PathWalkerImpl.startNewSegment
Javadoc:
No Javadoc available
Method code:
private void startNewSegment(IntLine line) {
it.nextSegment(currentSegment);
distanceAlongCurrentSegment = 0;
line.x1 = this.currentSegment.x1;
line.y1 = this.currentSegment.y1;
}
Outgoing Methods (calls):
jfreerails.world.train.PathWalkerImpl.stepForward
Javadoc:
/** * Specify the distance this PathWalker is to progress along the current * step. */
Method code:
/**
* Specify the distance this PathWalker is to progress along the current
* step.
*/
public void stepForward(double distance) {
distanceOfThisStepRemaining += distance;
}
No outgoing methods.
jfreerails.world.train.PathWalkerImplTest.assertHasNextEqualsFalse
Javadoc:
No Javadoc available
Method code:
void assertHasNextEqualsFalse(ArrayList<Point> points) {
FreerailsPathIterator it2 = FreerailsPathIteratorImpl
.forwardsIterator(points);
assertTrue(!it2.hasNext());
pw = new PathWalkerImpl(it2);
pw.stepForward(100);
assertTrue(!pw.hasNext());
}
Outgoing Methods (calls):
jfreerails.world.train.PathWalkerImplTest.assertLineEquals
Javadoc:
No Javadoc available
Method code:
private void assertLineEquals(int x1, int y1, int x2, int y2, IntLine line) {
assertEquals(x1, line.x1);
assertEquals(x2, line.x2);
assertEquals(y1, line.y1);
assertEquals(y2, line.y2);
}
No outgoing methods.
jfreerails.world.train.PathWalkerImplTest.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
junit.textui.TestRunner.run(PathWalkerImplTest.class);
}
No outgoing methods.
jfreerails.world.train.PathWalkerImplTest.moveToNextLimit
Javadoc:
No Javadoc available
Method code:
private void moveToNextLimit() {
IntLine line = new IntLine();
while (pw.hasNext()) {
pw.nextSegment(line);
}
}
Outgoing Methods (calls):
jfreerails.world.train.PathWalkerImplTest.setup
Javadoc:
No Javadoc available
Method code:
public void setup() {
int[] xpoints = { 0, 100, 100 };
int[] ypoints = { 0, 0, 100 };
it = new SimplePathIteratorImpl(xpoints, ypoints);
pw = new PathWalkerImpl(it);
}
No outgoing methods.
jfreerails.world.train.PathWalkerImplTest.testCanStepForward
Javadoc:
No Javadoc available
Method code:
/*
* Test for boolean canStepForward()
*/
public void testCanStepForward() {
setup();
assertTrue(pw.canStepForward());
pw.stepForward(500); // The path length is 200;
moveToNextLimit();
assertTrue(!pw.canStepForward());
setup();
assertTrue(pw.canStepForward());
pw.stepForward(10);
assertTrue(pw.canStepForward());
IntLine line = new IntLine();
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertLineEquals(0, 0, 10, 0, line);
assertTrue(!pw.hasNext());
assertTrue(pw.canStepForward());
pw.stepForward(500); // The path length is 200;
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertLineEquals(10, 0, 100, 0, line);
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertLineEquals(100, 0, 100, 100, line);
assertTrue(!pw.canStepForward());
}
Outgoing Methods (calls):
jfreerails.world.train.PathWalkerImplTest.testHasNext
Javadoc:
No Javadoc available
Method code:
public void testHasNext() {
IntLine line = new IntLine();
setup();
assertTrue(!pw.hasNext());
pw.stepForward(10);
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertLineEquals(0, 0, 10, 0, line);
assertTrue(!pw.hasNext());
setup();
assertTrue(!pw.hasNext());
pw.stepForward(110);
assertTrue(pw.hasNext());
line = new IntLine();
pw.nextSegment(line);
assertLineEquals(0, 0, 100, 0, line);
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertLineEquals(100, 0, 100, 10, line);
assertTrue(!pw.hasNext());
/*
* Now test with underlying pathIterators with few elements.
*/
ArrayList<Point> points = new ArrayList<Point>();
assertHasNextEqualsFalse(points);
points = new ArrayList<Point>();
points.add(new Point(0, 0));
assertHasNextEqualsFalse(points);
points = new ArrayList<Point>();
points.add(new Point(0, 0));
points.add(new Point(100, 0));
FreerailsPathIterator it2 = FreerailsPathIteratorImpl
.forwardsIterator(points);
assertTrue(it2.hasNext());
pw = new PathWalkerImpl(it2);
assertTrue(!pw.hasNext());
pw.stepForward(1000);
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertTrue(!pw.hasNext());
}
Outgoing Methods (calls):
jfreerails.world.train.Schedule.autoConsist
Javadoc:
/** Returns the value for the autoconsist flag at the next scheduled stop. */
Method code:
/** Returns the value for the autoconsist flag at the next scheduled stop. */
boolean autoConsist();
No outgoing methods.
jfreerails.world.train.Schedule.getNextScheduledOrder
Javadoc:
No Javadoc available
Method code:
int getNextScheduledOrder();
No outgoing methods.
jfreerails.world.train.Schedule.getNumOrders
Javadoc:
/** * Returns number of non priority orders + number of priority orders. * * @return Number of orders. */
Method code:
/**
* Returns number of non priority orders + number of priority orders.
*
* @return Number of orders.
*/
int getNumOrders();
No outgoing methods.
jfreerails.world.train.Schedule.getOrder
Javadoc:
No Javadoc available
Method code:
TrainOrdersModel getOrder(int i);
No outgoing methods.
jfreerails.world.train.Schedule.getOrderToGoto
Javadoc:
/** Returns the number of the order the train is currently carry out. */
Method code:
/** Returns the number of the order the train is currently carry out. */
int getOrderToGoto();
No outgoing methods.
jfreerails.world.train.Schedule.getStationToGoto
Javadoc:
/** * Returns the station number of the next station the train is scheduled to * stop at. */
Method code:
/**
* Returns the station number of the next station the train is scheduled to
* stop at.
*/
int getStationToGoto();
No outgoing methods.
jfreerails.world.train.Schedule.getWagonsToAdd
Javadoc:
/** Returns the wagons to add at the next scheduled stop. */
Method code:
/** Returns the wagons to add at the next scheduled stop. */
ImInts getWagonsToAdd();
No outgoing methods.
jfreerails.world.train.Schedule.hasPriorityOrders
Javadoc:
No Javadoc available
Method code:
boolean hasPriorityOrders();
No outgoing methods.
jfreerails.world.train.SimplePathIteratorImpl.hasNext
Javadoc:
No Javadoc available
Method code:
public boolean hasNext() {
return (position + 1) < x.size();
}
Outgoing Methods (calls):
jfreerails.world.train.SimplePathIteratorImpl.nextSegment
Javadoc:
No Javadoc available
Method code:
public void nextSegment(IntLine line) {
if (hasNext()) {
line.x1 = x.get(position);
line.y1 = y.get(position);
line.x2 = x.get(position + 1);
line.y2 = y.get(position + 1);
position++;
} else {
throw new NoSuchElementException();
}
}
Outgoing Methods (calls):
jfreerails.world.train.SimplePathIteratorImplTest.assertLineEquals
Javadoc:
No Javadoc available
Method code:
private void assertLineEquals(int x1, int y1, int x2, int y2, IntLine line) {
assertEquals(x1, line.x1);
assertEquals(x2, line.x2);
assertEquals(y1, line.y1);
assertEquals(y2, line.y2);
}
No outgoing methods.
jfreerails.world.train.SimplePathIteratorImplTest.main
Javadoc:
No Javadoc available
Method code:
public static void main(String[] args) {
junit.textui.TestRunner.run(SimplePathIteratorImplTest.class);
}
No outgoing methods.
jfreerails.world.train.SimplePathIteratorImplTest.testHasNext
Javadoc:
No Javadoc available
Method code:
public void testHasNext() {
int[] xpoints = { 0, 100 };
int[] ypoints = { 0, 0 };
FreerailsPathIterator it = new SimplePathIteratorImpl(xpoints, ypoints);
assertTrue(it.hasNext());
it.nextSegment(new IntLine(0, 0, 0, 0));
assertTrue(!it.hasNext());
}
Outgoing Methods (calls):
jfreerails.world.train.SimplePathIteratorImplTest.testNextSegment
Javadoc:
No Javadoc available
Method code:
public void testNextSegment() {
int[] xpoints = { 1, 2, 3 };
int[] ypoints = { 4, 5, 6 };
FreerailsPathIterator it = new SimplePathIteratorImpl(xpoints, ypoints);
assertTrue(it.hasNext());
IntLine line = new IntLine(0, 0, 0, 0);
it.nextSegment(line);
assertLineEquals(1, 4, 2, 5, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(2, 5, 3, 6, line);
assertTrue(!it.hasNext());
}
Outgoing Methods (calls):
jfreerails.world.train.SpeedAgainstTime.calcA
Javadoc:
/** * @throws IllegalArgumentException * iff t < 0 or t > getT() */
Method code:
/**
* @throws IllegalArgumentException
* iff t < 0 or t > getT()
*/
double calcA(double t);
No outgoing methods.
jfreerails.world.train.SpeedAgainstTime.calcS
Javadoc:
/** * Returns the distance travelled at time t. The returned value, s, * satisfies the following conditions: * <ol> * <li>s >= 0</li> * <li>s <= getS()</li> * <li>s = 0 if t = 0 </li> * <li>s = getS() if t = getT()</li> * </ol> * * @throws IllegalArgumentException * iff t < 0 or t > getT() * @return s */
Method code:
/**
* Returns the distance travelled at time t. The returned value, s,
* satisfies the following conditions:
* <ol>
* <li>s >= 0</li>
* <li>s <= getS()</li>
* <li>s = 0 if t = 0 </li>
* <li>s = getS() if t = getT()</li>
* </ol>
*
* @throws IllegalArgumentException
* iff t < 0 or t > getT()
* @return s
*/
double calcS(double t);
No outgoing methods.
jfreerails.world.train.SpeedAgainstTime.calcT
Javadoc:
/** * Returns the time taken to travel distance s. The returned value, t, * satisfies the following conditions: * <ol> * <li>t >= 0</li> * <li>t <= getT()</li> * <li>t = 0 if s = 0 </li> * <li>t = getT() if s = getS()</li> * </ol> * * @throws IllegalArgumentException * iff s < 0 or s > getS() * @return t */
Method code:
/**
* Returns the time taken to travel distance s. The returned value, t,
* satisfies the following conditions:
* <ol>
* <li>t >= 0</li>
* <li>t <= getT()</li>
* <li>t = 0 if s = 0 </li>
* <li>t = getT() if s = getS()</li>
* </ol>
*
* @throws IllegalArgumentException
* iff s < 0 or s > getS()
* @return t
*/
double calcT(double s);
No outgoing methods.
jfreerails.world.train.SpeedAgainstTime.calcV
Javadoc:
/** * @throws IllegalArgumentException * iff t < 0 or t > getT() */
Method code:
/**
* @throws IllegalArgumentException
* iff t < 0 or t > getT()
*/
double calcV(double t);
No outgoing methods.
jfreerails.world.train.SpeedAgainstTime.getS
Javadoc:
/** * @return The distance traveled during at time given by getT(). */
Method code:
/**
* @return The distance traveled during at time given by getT().
*/
double getS();
No outgoing methods.
jfreerails.world.train.SpeedAgainstTime.getT
Javadoc:
/** * @return The time taken to travel the distance given by getS(). */
Method code:
/**
* @return The time taken to travel the distance given by getS().
*/
double getT();
No outgoing methods.
jfreerails.world.train.SpeedTimeAndStatus.getActivity
Javadoc:
No Javadoc available
Method code:
public TrainActivity getActivity() {
return activity;
}
No outgoing methods.
jfreerails.world.train.TrainModel.canAddWagon
Javadoc:
No Javadoc available
Method code:
public boolean canAddWagon() {
return wagonTypes.size() < MAX_NUMBER_OF_WAGONS;
}
Outgoing Methods (calls):
jfreerails.world.train.TrainModel.getCargoBundleID
Javadoc:
No Javadoc available
Method code:
public int getCargoBundleID() {
return cargoBundleId;
}
No outgoing methods.
jfreerails.world.train.TrainModel.getConsist
Javadoc:
No Javadoc available
Method code:
public ImInts getConsist() {
return wagonTypes;
}
No outgoing methods.
jfreerails.world.train.TrainModel.getEngineType
Javadoc:
No Javadoc available
Method code:
public int getEngineType() {
return engineTypeId;
}
No outgoing methods.
jfreerails.world.train.TrainModel.getLength
Javadoc:
No Javadoc available
Method code:
public int getLength() {
return (1 + wagonTypes.size()) * WAGON_LENGTH; // Engine + wagons.
}
Outgoing Methods (calls):
jfreerails.world.train.TrainModel.getNewInstance
Javadoc:
No Javadoc available
Method code:
public TrainModel getNewInstance(int newEngine, ImInts newWagons) {
return new TrainModel(newEngine, newWagons, this.getScheduleID(), this
.getCargoBundleID());
}
Outgoing Methods (calls):
jfreerails.world.train.TrainModel.getNumberOfWagons
Javadoc:
No Javadoc available
Method code:
public int getNumberOfWagons() {
return wagonTypes.size();
}
Outgoing Methods (calls):
jfreerails.world.train.TrainModel.getScheduleID
Javadoc:
No Javadoc available
Method code:
public int getScheduleID() {
return scheduleId;
}
No outgoing methods.
jfreerails.world.train.TrainModel.getWagon
Javadoc:
No Javadoc available
Method code:
public int getWagon(int i) {
return wagonTypes.get(i);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainMotion.calcOffSet
Javadoc:
No Javadoc available
Method code:
private double calcOffSet(double t) {
double offset = getDistance(t) + initialPosition - trainLength;
return offset;
}
Outgoing Methods (calls):
jfreerails.world.train.TrainMotion.checkT
Javadoc:
No Javadoc available
Method code:
void checkT(double t) {
if (t < 0d || t > duration)
throw new IllegalArgumentException("t=" + t + ", but duration="
+ duration);
}
No outgoing methods.
jfreerails.world.train.TrainMotion.duration
Javadoc:
No Javadoc available
Method code:
public double duration() {
return duration;
}
No outgoing methods.
jfreerails.world.train.TrainMotion.getActivity
Javadoc:
No Javadoc available
Method code:
public SpeedTimeAndStatus.TrainActivity getActivity() {
return activity;
}
No outgoing methods.
jfreerails.world.train.TrainMotion.getDistance
Javadoc:
/** * Returns the train's distance along the track from the point the train was * at at time <code>getStart()</code> at the specified time. * * @param t * the time. * @return the distance * @throws IllegalArgumentException * if t is outside the interval */
Method code:
/**
* Returns the train's distance along the track from the point the train was
* at at time <code>getStart()</code> at the specified time.
*
* @param t
* the time.
* @return the distance
* @throws IllegalArgumentException
* if t is outside the interval
*/
public double getDistance(double t) {
checkT(t);
t = Math.min(t, speeds.getT());
return speeds.calcS(t);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainMotion.getFinalPosition
Javadoc:
No Javadoc available
Method code:
public PositionOnTrack getFinalPosition() {
return path.getFinalPosition();
}
Outgoing Methods (calls):
jfreerails.world.train.TrainMotion.getInitialPosition
Javadoc:
No Javadoc available
Method code:
public double getInitialPosition() {
return initialPosition;
}
No outgoing methods.
jfreerails.world.train.TrainMotion.getPath
Javadoc:
/** * Returns the current path that the train is following. * This method provides access to the internal path representation * which details the route the train is taking across tiles. * * @return the PathOnTiles object representing the train's current path */
Method code:
public PathOnTiles getPath() {
return path;
}
No outgoing methods.
jfreerails.world.train.TrainMotion.getSpeedAtEnd
Javadoc:
No Javadoc available
Method code:
public double getSpeedAtEnd() {
double finalT = speeds.getT();
return speeds.calcV(finalT);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainMotion.getState
Javadoc:
/** * Returns the train's position at the specified time. * * @param t * the time. * @return the train's position. * @throws IllegalArgumentException * if t is outside the interval */
Method code:
/**
* Returns the train's position at the specified time.
*
* @param t
* the time.
* @return the train's position.
* @throws IllegalArgumentException
* if t is outside the interval
*/
public TrainPositionOnMap getState(double t) {
t = Math.min(t, speeds.getT());
double offset = calcOffSet(t);
FreerailsPathIterator pathIt = path.subPath(offset, trainLength);
double speed = speeds.calcV(t);
double acceleration = speeds.calcA(t);
TrainPositionOnMap tpom = TrainPositionOnMap
.createInSameDirectionAsPath(pathIt, speed, acceleration,
activity);
return tpom.reverse();
}
Outgoing Methods (calls):
jfreerails.world.train.TrainMotion.getTiles
Javadoc:
/** * Returns a PathOnTiles object that identifies the tiles the train is on at * the specified time. * * @param t * the time. * @return an array of the tiles the train is on * @throws IllegalArgumentException * if t is outside the interval */
Method code:
/**
* Returns a PathOnTiles object that identifies the tiles the train is on at
* the specified time.
*
* @param t
* the time.
* @return an array of the tiles the train is on
* @throws IllegalArgumentException
* if t is outside the interval
*/
public PathOnTiles getTiles(double t) {
checkT(t);
t = Math.min(t, speeds.getT());
double start = calcOffSet(t);
double end = start + trainLength;
ArrayList<Step> steps = new ArrayList<Step>();
double distanceSoFar = 0;
int stepsBeforeStart = 0;
int stepsAfterEnd = 0;
for (int i = 0; i < path.steps(); i++) {
if (distanceSoFar > end)
stepsAfterEnd++;
Step step = path.getStep(i);
distanceSoFar += step.getLength();
if (distanceSoFar < start)
stepsBeforeStart++;
}
if (distanceSoFar < start) {
// throw new IllegalStateException();
}
if (distanceSoFar < (end - 0.1)) {
// throw new IllegalStateException();
}
int lastStep = path.steps() - stepsAfterEnd;
for (int i = stepsBeforeStart; i < lastStep; i++) {
steps.add(path.getStep(i));
}
ImPoint p = path.getStart();
int x = p.x;
int y = p.y;
for (int i = 0; i < stepsBeforeStart; i++) {
Step step = path.getStep(i);
x += step.deltaX;
y += step.deltaY;
}
ImPoint startPoint = new ImPoint(x, y);
PathOnTiles pathOnTiles = new PathOnTiles(startPoint, steps);
return pathOnTiles;
}
Outgoing Methods (calls):
jfreerails.world.train.TrainMotion.getTrainLength
Javadoc:
No Javadoc available
Method code:
public int getTrainLength() {
return trainLength;
}
No outgoing methods.
jfreerails.world.train.TrainMotion.sanityCheck
Javadoc:
/** Checks we are not creating an object with an inconsistent state. That is, at the * time stored in the field duration, the engine must not have gone off the end of the path.*/
Method code:
/** Checks we are not creating an object with an inconsistent state. That is, at the
* time stored in the field duration, the engine must not have gone off the end of the path.*/
private void sanityCheck() {
double offset = calcOffSet(duration);
double totalLength = path.getTotalDistance();
double trainLengthDouble = trainLength;
if(totalLength < offset + trainLengthDouble)
throw new IllegalStateException(offset +" + "+ trainLengthDouble+" > " +totalLength);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainMotionTest.test4Bug1266695
Javadoc:
No Javadoc available
Method code:
public void test4Bug1266695(){
//The figures are copied from the debugger.
ImPoint start = new ImPoint(14, 5);
Step[] vectors= {Step.getInstance(1,1), Step.getInstance(1,0)};
PathOnTiles path = new PathOnTiles(start, vectors);
ConstAcc constAcc0 = ConstAcc.uat(6.5135556243263055d, 0.5d, 6.972888751347389d);
ConstAcc constAcc1 = ConstAcc.uat(10.0, 0.0d, 4.0d);
SpeedAgainstTime speeds = new CompositeSpeedAgainstTime(constAcc0, constAcc1);
double expectedTotalDistance= 97.57359312880715d; //Copied from debugger.
double actualTotalDistance = speeds.getS();
assertEquals(expectedTotalDistance, actualTotalDistance,0d);
double expectedDuration = 10.972888751347389d;
double actualDuration = speeds.getT();
assertEquals(expectedDuration, actualDuration,0d);
int engineStep = 1;
int trainLength = 24;
TrainMotion motion = new TrainMotion(path,engineStep, trainLength, speeds);
double expectedInitialPosition = 42.42640687119285;
double actualInitialPosition = motion.getInitialPosition();
assertEquals(expectedInitialPosition, actualInitialPosition,0d);
//Different from above
double tooLongDuration = 3.9936298481613424d;
actualDuration = motion.duration();
assertTrue(tooLongDuration > actualDuration);
//This method used to throw an exception
@SuppressWarnings("unused") Object o = motion.getState(actualDuration);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainOrdersModel.getConsist
Javadoc:
/** * @return either (1) an array of cargo type ids or (2) null to represent * 'no change'. */
Method code:
/**
* @return either (1) an array of cargo type ids or (2) null to represent
* 'no change'.
*/
public ImInts getConsist() {
return this.consist;
}
No outgoing methods.
jfreerails.world.train.TrainOrdersModel.getStationID
Javadoc:
No Javadoc available
Method code:
public int getStationID() {
return stationId;
}
No outgoing methods.
jfreerails.world.train.TrainOrdersModel.getWaitUntilFull
Javadoc:
No Javadoc available
Method code:
public boolean getWaitUntilFull() {
return waitUntilFull;
}
No outgoing methods.
jfreerails.world.train.TrainOrdersModel.hasLessThanMaximumNumberOfWagons
Javadoc:
No Javadoc available
Method code:
public boolean hasLessThanMaximumNumberOfWagons() {
return null == consist || consist.size() < MAXIMUM_NUMBER_OF_WAGONS;
}
Outgoing Methods (calls):
jfreerails.world.train.TrainOrdersModel.isAutoConsist
Javadoc:
No Javadoc available
Method code:
public boolean isAutoConsist() {
return autoConsist;
}
No outgoing methods.
jfreerails.world.train.TrainOrdersModel.isNoConsistChange
Javadoc:
No Javadoc available
Method code:
public boolean isNoConsistChange() {
return null == consist;
}
No outgoing methods.
jfreerails.world.train.TrainOrdersModel.orderHasWagons
Javadoc:
No Javadoc available
Method code:
public boolean orderHasWagons() {
return null != consist && 0 != consist.size();
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPathIterator.hasNext
Javadoc:
No Javadoc available
Method code:
public boolean hasNext() {
return intIterator.hasNextInt();
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPathIterator.nextSegment
Javadoc:
No Javadoc available
Method code:
public void nextSegment(IntLine line) {
p1.setValuesFromInt(p2.toInt());
line.x1 = p1.getX() * tileSize + tileSize / 2;
line.y1 = p1.getY() * tileSize + tileSize / 2;
p2.setValuesFromInt(intIterator.nextInt());
line.x2 = p2.getX() * tileSize + tileSize / 2;
line.y2 = p2.getY() * tileSize + tileSize / 2;
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.aHeadEqualsBTail
Javadoc:
No Javadoc available
Method code:
public static boolean aHeadEqualsBTail(TrainPositionOnMap a,
TrainPositionOnMap b) {
int aHeadX = a.getX(0);
int aHeadY = a.getY(0);
int bTailX = b.getX(b.getLength() - 1);
int bTailY = b.getY(b.getLength() - 1);
if (aHeadX == bTailX && aHeadY == bTailY) {
return true;
}
return false;
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.addBtoHeadOfA
Javadoc:
No Javadoc available
Method code:
private TrainPositionOnMap addBtoHeadOfA(TrainPositionOnMap b,
TrainPositionOnMap a) {
if (aHeadEqualsBTail(a, b)) {
int newLength = a.getLength() + b.getLength() - 2;
int[] newXpoints = new int[newLength];
int[] newYpoints = new int[newLength];
int aLength = a.getLength();
int bLength = b.getLength();
// First copy the points from B
for (int i = 0; i < bLength - 1; i++) {
newXpoints[i] = b.getX(i);
newYpoints[i] = b.getY(i);
}
// Second copy the points from A.
for (int i = 1; i < aLength; i++) {
newXpoints[i + bLength - 2] = a.getX(i);
newYpoints[i + bLength - 2] = a.getY(i);
}
return new TrainPositionOnMap(newXpoints, newYpoints,
b.acceleration, b.speed, b.activity);
}
throw new IllegalArgumentException("Tried to add " + b.toString()
+ " to the head of " + a.toString());
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.addToHead
Javadoc:
/** * Adds the specified train position to the head of this train's position list. * This method creates a new TrainPositionOnMap instance where the given position * is placed at the head (front) of the sequence. The original position remains unchanged. * * @param b the TrainPositionOnMap instance to add to the head of this position * @return a new TrainPositionOnMap instance with the specified position added to the head */
Method code:
public TrainPositionOnMap addToHead(TrainPositionOnMap b) {
TrainPositionOnMap a = this;
return addBtoHeadOfA(b, a);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.addToTail
Javadoc:
No Javadoc available
Method code:
public TrainPositionOnMap addToTail(TrainPositionOnMap a) {
TrainPositionOnMap b = this;
return addBtoHeadOfA(b, a);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.bHeadEqualsATail
Javadoc:
No Javadoc available
Method code:
public static boolean bHeadEqualsATail(TrainPositionOnMap a,
TrainPositionOnMap b) {
return aHeadEqualsBTail(b, a);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.calculateDistance
Javadoc:
No Javadoc available
Method code:
public double calculateDistance() {
double distance = 0;
IntLine line = new IntLine();
FreerailsPathIterator path = this.path();
while (path.hasNext()) {
path.nextSegment(line);
int sumOfSquares = (line.x1 - line.x2) * (line.x1 - line.x2)
+ (line.y1 - line.y2) * (line.y1 - line.y2);
distance += Math.sqrt(sumOfSquares);
}
return distance;
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.canAddToHead
Javadoc:
No Javadoc available
Method code:
public boolean canAddToHead(TrainPositionOnMap b) {
return aHeadEqualsBTail(this, b);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.canAddToTail
Javadoc:
No Javadoc available
Method code:
public boolean canAddToTail(TrainPositionOnMap b) {
return aHeadEqualsBTail(b, this);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.canRemoveFromHead
Javadoc:
No Javadoc available
Method code:
public boolean canRemoveFromHead(TrainPositionOnMap b) {
if (headsAreEqual(this, b)) {
FreerailsPathIterator path = b.path();
int i = 0;
IntLine line = new IntLine();
while (path.hasNext()) {
path.nextSegment(line);
if (this.getX(i) != line.x1 || this.getY(i) != line.y1) {
return false;
}
i++;
}
return true;
}
return false;
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.canRemoveFromTail
Javadoc:
No Javadoc available
Method code:
public boolean canRemoveFromTail(TrainPositionOnMap b) {
if (tailsAreEqual(this, b)) {
FreerailsPathIterator path = b.reversePath();
int i = this.getLength() - 1;
IntLine line = new IntLine();
while (path.hasNext()) {
path.nextSegment(line);
if (this.getX(i) != line.x1 || this.getY(i) != line.y1) {
return false;
}
i--;
}
return true;
}
return false;
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.createInSameDirectionAsPath
Javadoc:
No Javadoc available
Method code:
public static TrainPositionOnMap createInSameDirectionAsPath(
FreerailsPathIterator path) {
return createInSameDirectionAsPath(path, 0d, 0d,
SpeedTimeAndStatus.TrainActivity.READY);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.createInstance
Javadoc:
No Javadoc available
Method code:
public static TrainPositionOnMap createInstance(int[] xpoints, int[] ypoints) {
return new TrainPositionOnMap(xpoints, ypoints, 0d, 0d,
SpeedTimeAndStatus.TrainActivity.READY);
}
No outgoing methods.
jfreerails.world.train.TrainPositionOnMap.getAcceleration
Javadoc:
No Javadoc available
Method code:
public double getAcceleration() {
return acceleration;
}
No outgoing methods.
jfreerails.world.train.TrainPositionOnMap.getActivity
Javadoc:
No Javadoc available
Method code:
public SpeedTimeAndStatus.TrainActivity getActivity() {
return activity;
}
No outgoing methods.
jfreerails.world.train.TrainPositionOnMap.getFrameCt
Javadoc:
No Javadoc available
Method code:
public int getFrameCt() {
return frameCt;
}
No outgoing methods.
jfreerails.world.train.TrainPositionOnMap.getLength
Javadoc:
No Javadoc available
Method code:
public int getLength() {
return xpoints.size();
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.getSpeed
Javadoc:
No Javadoc available
Method code:
public double getSpeed() {
return speed;
}
No outgoing methods.
jfreerails.world.train.TrainPositionOnMap.getX
Javadoc:
No Javadoc available
Method code:
public int getX(int position) {
return xpoints.get(position);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.getXPoints
Javadoc:
No Javadoc available
Method code:
public ImInts getXPoints() {
return xpoints;
}
No outgoing methods.
jfreerails.world.train.TrainPositionOnMap.getY
Javadoc:
No Javadoc available
Method code:
public int getY(int position) {
return ypoints.get(position);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.getYPoints
Javadoc:
No Javadoc available
Method code:
public ImInts getYPoints() {
return ypoints;
}
No outgoing methods.
jfreerails.world.train.TrainPositionOnMap.headsAreEqual
Javadoc:
No Javadoc available
Method code:
public static boolean headsAreEqual(TrainPositionOnMap a,
TrainPositionOnMap b) {
int aHeadX = a.getX(0);
int aHeadY = a.getY(0);
int bHeadX = b.getX(0);
int bHeadY = b.getY(0);
if (aHeadX == bHeadX && aHeadY == bHeadY) {
return true;
}
return false;
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.incrementFramCt
Javadoc:
No Javadoc available
Method code:
public void incrementFramCt() {
if (frame > 0) {
incrementFrame();
frame = 0;
} else {
frame++;
}
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.incrementFrame
Javadoc:
No Javadoc available
Method code:
public void incrementFrame() {
frameCt++;
}
No outgoing methods.
jfreerails.world.train.TrainPositionOnMap.isCrashSite
Javadoc:
No Javadoc available
Method code:
public boolean isCrashSite() {
return crashSite;
}
No outgoing methods.
jfreerails.world.train.TrainPositionOnMap.path
Javadoc:
No Javadoc available
Method code:
public FreerailsPathIterator path() {
return new SimplePathIteratorImpl(this.xpoints, this.ypoints);
}
No outgoing methods.
jfreerails.world.train.TrainPositionOnMap.removeFromHead
Javadoc:
No Javadoc available
Method code:
public TrainPositionOnMap removeFromHead(TrainPositionOnMap b) {
if (headsAreEqual(this, b)) {
int newLength = this.getLength() - b.getLength() + 2;
int[] newXpoints = new int[newLength];
int[] newYpoints = new int[newLength];
int bLength = b.getLength();
// copy head from b
int bHeadPosition = b.getLength() - 1;
newXpoints[0] = b.getX(bHeadPosition);
newYpoints[0] = b.getY(bHeadPosition);
// Copy rest from this
for (int i = 1; i < newLength; i++) {
int position = bLength + i - 2;
newXpoints[i] = this.getX(position);
newYpoints[i] = this.getY(position);
}
return new TrainPositionOnMap(newXpoints, newYpoints, speed,
acceleration, activity);
}
throw new IllegalArgumentException();
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.removeFromTail
Javadoc:
No Javadoc available
Method code:
public TrainPositionOnMap removeFromTail(TrainPositionOnMap b) {
if (tailsAreEqual(this, b)) {
int newLength = this.getLength() - b.getLength() + 2;
int[] newXpoints = new int[newLength];
int[] newYpoints = new int[newLength];
// Copy from this
for (int i = 0; i < newLength - 1; i++) {
newXpoints[i] = this.getX(i);
newYpoints[i] = this.getY(i);
}
// Copy tail from b
newXpoints[newLength - 1] = b.getX(0);
newYpoints[newLength - 1] = b.getY(0);
return new TrainPositionOnMap(newXpoints, newYpoints, speed,
acceleration, activity);
}
throw new IllegalArgumentException();
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.reverse
Javadoc:
/** * Returns a new TrainPositionOnMap instance with the coordinates reversed. * This method creates a new TrainPositionOnMap object where the xpoints and ypoints * arrays are reversed in order, while preserving the speed, acceleration, and * activity values from the original instance. * * @return A new TrainPositionOnMap instance representing the reversed position. */
Method code:
public TrainPositionOnMap reverse() {
int length = xpoints.size();
int[] reversed_xpoints = new int[length];
int[] reversed_ypoints = new int[length];
for (int i = 0; i < length; i++) {
reversed_xpoints[i] = xpoints.get(length - i - 1);
reversed_ypoints[i] = ypoints.get(length - i - 1);
}
return new TrainPositionOnMap(reversed_xpoints, reversed_ypoints,
speed, acceleration, activity);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.reversePath
Javadoc:
No Javadoc available
Method code:
public FreerailsPathIterator reversePath() {
int length = xpoints.size();
int[] reversed_xpoints = new int[length];
int[] reversed_ypoints = new int[length];
for (int i = 0; i < length; i++) {
reversed_xpoints[i] = xpoints.get(length - i - 1);
reversed_ypoints[i] = ypoints.get(length - i - 1);
}
return new SimplePathIteratorImpl(reversed_xpoints, reversed_ypoints);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMap.setCrashSite
Javadoc:
No Javadoc available
Method code:
public void setCrashSite(boolean isCrash) {
crashSite = isCrash;
}
No outgoing methods.
jfreerails.world.train.TrainPositionOnMap.tailsAreEqual
Javadoc:
No Javadoc available
Method code:
public static boolean tailsAreEqual(TrainPositionOnMap a,
TrainPositionOnMap b) {
int aTailX = a.getX(a.getLength() - 1);
int aTailY = a.getY(a.getLength() - 1);
int bTailX = b.getX(b.getLength() - 1);
int bTailY = b.getY(b.getLength() - 1);
if (aTailX == bTailX && aTailY == bTailY) {
return true;
}
return false;
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMapTest.testAddToHead
Javadoc:
No Javadoc available
Method code:
/*
* public void testAdd() { TrainPosition a, b, c, d, e, f, g, h , i, j;
* a=TrainPosition.createInstance(new int[] {10,20}, new int[]{11,22});
* b=TrainPosition.createInstance(new int[] {20, 30}, new int[]{22,33});
* c=TrainPosition.createInstance(new int[] {10, 30}, new int[]{11, 33});
*
* d=TrainPosition.add(a, b); assertEquals(d, c); e=TrainPosition.add(b, a);
* assertEquals(e, c);
*
*
* f = TrainPosition.createInstance( new int[] { 40, 50 }, new int[] { 44,
* 55 }); g = TrainPosition.createInstance( new int[] { 10, 30, 40 }, new
* int[] { 11, 33, 44 });
*
* i = TrainPosition.createInstance( new int[] { 10, 30, 50 }, new int[] {
* 11, 33, 55 }); j = TrainPosition.add(f, g); assertEquals(i, j);
*
*
* }
*/
/*
* public void testRemove() { TrainPosition a, b, c, d, e, f, g, h , i, j ,
* k; a=TrainPosition.createInstance(new int[] {10,20 ,40 , 50, 60}, new
* int[]{11,22, 44, 55 , 66}); b=TrainPosition.createInstance(new int[] {10,
* 20, 30}, new int[]{11,22,33}); c=TrainPosition.createInstance(new int[]
* {48, 50, 60}, new int[]{49,55, 66});
*
* d=TrainPosition.createInstance(new int[] {30, 40 , 50, 60}, new int[]{33,
* 44, 55, 66}); e=TrainPosition.createInstance(new int[] {10, 20, 40, 48},
* new int[]{11, 22, 44, 49});
*
* f=TrainPosition.remove(a, b); assertEquals(f, d);
*
* g=TrainPosition.remove(a, c); assertEquals(g, e);
*
* h = TrainPosition.createInstance( new int[] { 10, 30, 50 }, new int[] {
* 11, 33, 55 });
*
* i = TrainPosition.createInstance( new int[] { 10, 20 }, new int[] { 11,
* 22 });
*
* j = TrainPosition.createInstance( new int[] { 20, 30, 50 }, new int[] {
* 22, 33, 55 });
*
* k = TrainPosition.remove(h, i);
*
* assertEquals(k, j); }
*
*/
/*
* public void testCanBeAdded() { TrainPosition a, b, c, d;
* a=TrainPosition.createInstance(new int[] {10,20}, new int[]{11,22});
* b=TrainPosition.createInstance(new int[] {20, 30}, new int[]{22,33});
* c=TrainPosition.createInstance(new int[] {30, 40}, new int[]{33,44});
*
* assertTrue(TrainPosition.canBeAdded(a, b));
* assertTrue(TrainPosition.canBeAdded(b, a));
* assertTrue(TrainPosition.canBeAdded(b, c));
* assertTrue(!TrainPosition.canBeAdded(c, b));
*
* assertTrue(!TrainPosition.canBeAdded(a, c));
* assertTrue(!TrainPosition.canBeAdded(c, a));
*
* //Test that we cannot add a position to itself
* assertTrue(!TrainPosition.canBeAdded(a, a));
* assertTrue(!TrainPosition.canBeAdded(b, b));
* assertTrue(!TrainPosition.canBeAdded(c, c)); }
*/
/*
* public void testCanBeRemoved() { TrainPosition a, b, c, d;
* a=TrainPosition.createInstance(new int[] {10,20 ,40 , 50}, new
* int[]{11,22, 44, 55}); b=TrainPosition.createInstance(new int[] {10, 20,
* 30}, new int[]{11,22,33}); c=TrainPosition.createInstance(new int[] {30,
* 40, 50}, new int[]{33,44,55});
*
* assertTrue(TrainPosition.canBeRemoved(a, b));
*
* assertTrue(!TrainPosition.canBeRemoved(b, a));
*
* assertTrue(TrainPosition.canBeRemoved(a, c));
*
* assertTrue(!TrainPosition.canBeRemoved(c, a));
*
* //Test that we cannot remove a position from itself
* assertTrue(!TrainPosition.canBeRemoved(a, a));
* assertTrue(!TrainPosition.canBeRemoved(b, b));
* assertTrue(!TrainPosition.canBeRemoved(c, c)); }
*/
public void testAddToHead() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
TrainPositionOnMap d;
TrainPositionOnMap f;
TrainPositionOnMap g;
TrainPositionOnMap i;
TrainPositionOnMap j;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
b = TrainPositionOnMap.createInstance(new int[] { 20, 30 }, new int[] {
22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 10, 30 }, new int[] {
11, 33 });
d = b.addToHead(a);
assertEquals(d, c);
f = TrainPositionOnMap.createInstance(new int[] { 40, 50 }, new int[] {
44, 55 });
g = TrainPositionOnMap.createInstance(new int[] { 10, 30, 40 },
new int[] { 11, 33, 44 });
i = TrainPositionOnMap.createInstance(new int[] { 10, 30, 50 },
new int[] { 11, 33, 55 });
j = f.addToHead(g);
assertEquals(i, j);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMapTest.testAddToTail
Javadoc:
No Javadoc available
Method code:
public void testAddToTail() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
TrainPositionOnMap d;
TrainPositionOnMap f;
TrainPositionOnMap g;
TrainPositionOnMap i;
TrainPositionOnMap j;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
b = TrainPositionOnMap.createInstance(new int[] { 20, 30 }, new int[] {
22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 10, 30 }, new int[] {
11, 33 });
d = a.addToTail(b);
assertEquals(d, c);
f = TrainPositionOnMap.createInstance(new int[] { 40, 50 }, new int[] {
44, 55 });
g = TrainPositionOnMap.createInstance(new int[] { 10, 30, 40 },
new int[] { 11, 33, 44 });
i = TrainPositionOnMap.createInstance(new int[] { 10, 30, 50 },
new int[] { 11, 33, 55 });
j = g.addToTail(f);
assertEquals(i, j);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMapTest.testCanAddToHead
Javadoc:
No Javadoc available
Method code:
public void testCanAddToHead() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
b = TrainPositionOnMap.createInstance(new int[] { 20, 30 }, new int[] {
22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 30, 40 }, new int[] {
33, 44 });
assertTrue(b.canAddToHead(a));
assertTrue(!a.canAddToHead(b));
assertTrue(c.canAddToHead(b));
assertTrue(!b.canAddToHead(c));
assertTrue(!c.canAddToHead(a));
assertTrue(!a.canAddToHead(c));
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMapTest.testCanAddToTail
Javadoc:
No Javadoc available
Method code:
public void testCanAddToTail() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
b = TrainPositionOnMap.createInstance(new int[] { 20, 30 }, new int[] {
22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 30, 40 }, new int[] {
33, 44 });
assertTrue(!b.canAddToTail(a));
assertTrue(a.canAddToTail(b));
assertTrue(!c.canAddToTail(b));
assertTrue(b.canAddToTail(c));
assertTrue(!c.canAddToTail(a));
assertTrue(!a.canAddToTail(c));
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMapTest.testCanRemoveFromHead
Javadoc:
No Javadoc available
Method code:
public void testCanRemoveFromHead() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20, 40, 50 },
new int[] { 11, 22, 44, 55 });
b = TrainPositionOnMap.createInstance(new int[] { 10, 20, 30 },
new int[] { 11, 22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 30, 40, 50 },
new int[] { 33, 44, 55 });
assertTrue(!b.canRemoveFromHead(a));
assertTrue(a.canRemoveFromHead(b));
assertTrue(!c.canRemoveFromHead(b));
assertTrue(!b.canRemoveFromHead(c));
assertTrue(!c.canRemoveFromHead(a));
assertTrue(!a.canRemoveFromHead(c));
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMapTest.testCanRemoveFromTail
Javadoc:
No Javadoc available
Method code:
public void testCanRemoveFromTail() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20, 40, 50 },
new int[] { 11, 22, 44, 55 });
b = TrainPositionOnMap.createInstance(new int[] { 10, 20, 30 },
new int[] { 11, 22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 30, 40, 50 },
new int[] { 33, 44, 55 });
assertTrue(!b.canRemoveFromTail(a));
assertTrue(!a.canRemoveFromTail(b));
assertTrue(!c.canRemoveFromTail(b));
assertTrue(!b.canRemoveFromTail(c));
assertTrue(!c.canRemoveFromTail(a));
assertTrue(a.canRemoveFromTail(c));
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMapTest.testCreateInOppositeDirectionToPath
Javadoc:
/** * Tests that reversing a TrainPositionOnMap created with createInSameDirectionAsPath * results in the expected coordinates when the path is defined with specific points. */
Method code:
public void testCreateInOppositeDirectionToPath() {
FreerailsPathIterator path = new SimplePathIteratorImpl(new int[] { 40,
30, 20, 10 }, new int[] { 44, 33, 22, 11 });
TrainPositionOnMap a = TrainPositionOnMap.createInSameDirectionAsPath(
path).reverse();
assertEquals(a.getLength(), 4);
assertEquals(a.getX(3), 40);
assertEquals(a.getY(3), 44);
assertEquals(a.getX(2), 30);
assertEquals(a.getY(2), 33);
assertEquals(a.getX(1), 20);
assertEquals(a.getY(1), 22);
assertEquals(a.getX(0), 10);
assertEquals(a.getY(0), 11);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMapTest.testCreateInstanceFreerailsPathIterator
Javadoc:
No Javadoc available
Method code:
/*
* Test for TrainPosition createInstance(FreerailsPathIterator)
*/
public void testCreateInstanceFreerailsPathIterator() {
FreerailsPathIterator path = new SimplePathIteratorImpl(new int[] { 40,
30, 20, 10 }, new int[] { 44, 33, 22, 11 });
TrainPositionOnMap a = TrainPositionOnMap
.createInSameDirectionAsPath(path);
assertEquals(a.getLength(), 4);
assertEquals(a.getX(0), 40);
assertEquals(a.getY(0), 44);
assertEquals(a.getX(1), 30);
assertEquals(a.getY(1), 33);
assertEquals(a.getX(2), 20);
assertEquals(a.getY(2), 22);
assertEquals(a.getX(3), 10);
assertEquals(a.getY(3), 11);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMapTest.testCreateInstanceIArrayIArray
Javadoc:
No Javadoc available
Method code:
/*
* Test for TrainPosition createInstance(int[], int[])
*/
public void testCreateInstanceIArrayIArray() {
try {
TrainPositionOnMap.createInstance(new int[] { 40, 30, 20, 10 },
new int[] { 44, 33, 22, 11 });
} catch (Exception e) {
assertTrue(false);
}
try {
TrainPositionOnMap.createInstance(new int[] { 40, 30, 20 },
new int[] { 44, 33, 22, 11 });
assertTrue(false);
} catch (Exception e) {
}
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMapTest.testEquals
Javadoc:
No Javadoc available
Method code:
public void testEquals() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
b = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
c = TrainPositionOnMap.createInstance(new int[] { 30, 40 }, new int[] {
33, 44 });
assertTrue(!a.equals(null));
assertTrue(!a.equals(new Object()));
assertTrue(a.equals(a));
assertTrue(a.equals(b));
assertTrue(!a.equals(c));
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMapTest.testGetLength
Javadoc:
No Javadoc available
Method code:
public void testGetLength() {
TrainPositionOnMap a;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20, 30, 40 },
new int[] { 11, 22, 33, 44 });
assertEquals(4, a.getLength());
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMapTest.testGetPoint
Javadoc:
No Javadoc available
Method code:
public void testGetPoint() {
TrainPositionOnMap a;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
assertEquals(a.getX(0), 10);
assertEquals(a.getY(0), 11);
assertEquals(a.getX(1), 20);
assertEquals(a.getY(1), 22);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMapTest.testPath
Javadoc:
No Javadoc available
Method code:
public void testPath() {
TrainPositionOnMap a;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20, 30, 40 },
new int[] { 11, 22, 33, 44 });
FreerailsPathIterator path = a.path();
IntLine line = new IntLine();
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(10, 11, 20, 22));
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(20, 22, 30, 33));
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(30, 33, 40, 44));
assertTrue(!path.hasNext());
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMapTest.testRemoveFromTail
Javadoc:
No Javadoc available
Method code:
public void testRemoveFromTail() {
TrainPositionOnMap a;
TrainPositionOnMap c;
TrainPositionOnMap e;
TrainPositionOnMap f;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20, 40, 50, 60 },
new int[] { 11, 22, 44, 55, 66 });
c = TrainPositionOnMap.createInstance(new int[] { 48, 50, 60 },
new int[] { 49, 55, 66 });
e = TrainPositionOnMap.createInstance(new int[] { 10, 20, 40, 48 },
new int[] { 11, 22, 44, 49 });
f = a.removeFromTail(c);
assertEquals(e, f);
}
Outgoing Methods (calls):
jfreerails.world.train.TrainPositionOnMapTest.testReversePath
Javadoc:
No Javadoc available
Method code:
public void testReversePath() {
TrainPositionOnMap a;
a = TrainPositionOnMap.createInstance(new int[] { 40, 30, 20, 10 },
new int[] { 44, 33, 22, 11 });
FreerailsPathIterator path = a.reversePath();
IntLine line = new IntLine();
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(10, 11, 20, 22));
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(20, 22, 30, 33));
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(30, 33, 40, 44));
assertTrue(!path.hasNext());
}
Outgoing Methods (calls):
jfreerails.world.train.WagonType.getCategory
Javadoc:
No Javadoc available
Method code:
public int getCategory() {
return typeCategory;
}
No outgoing methods.
jfreerails.world.train.WagonType.getName
Javadoc:
No Javadoc available
Method code:
public String getName() {
return typeName;
}
No outgoing methods.